1

I couldn't find similar issues here. Correct me please if I'm duplicating the topic.

I created a User Control:

    <UserControl x:Class="Toolbox.ctrl.LabeledTextBox"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:Toolbox.ctrl"
             mc:Ignorable="d" 
             >
    <StackPanel>
        <Label Content="{Binding Label}" FontSize="10" Height="25" Foreground="{StaticResource MainFontColor}" VerticalContentAlignment="Bottom"/>
        <TextBox Text="{Binding Body}" Height="25" FontSize="12"/>
    </StackPanel>
</UserControl>

class:

public partial class LabeledTextBox : UserControl
{
    public static readonly DependencyProperty LabelProperty = DependencyProperty.Register("Label", typeof(String), typeof(LabeledTextBox));
    public static readonly DependencyProperty BodyProperty = DependencyProperty.Register("Body", typeof(String), typeof(LabeledTextBox));

    public string Label
    {
        get { return (string)GetValue(LabelProperty); }
        set { SetValue(LabelProperty, value); }
    }

    public string Body
    {
        get { return (string)GetValue(BodyProperty); }
        set { SetValue(BodyProperty, value); }
    }

    public LabeledTextBox()
    {
        InitializeComponent();
        this.DataContext = this;
    }
}

And I use it in MainWindow.xaml:

<Grid x:Name="SomeGrid">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="1*"/>
            <ColumnDefinition Width="2*"/>
            <ColumnDefinition Width="1*"/>
        </Grid.ColumnDefinitions>
        <ctrl:LabeledTextBox Grid.Column="0" Label="Site ID:" Body="{Binding SiteID}" />
        <ctrl:LabeledTextBox Grid.Column="1" Label="Site Name:" Body="{Binding SiteName}" Margin="5,0,0,0"/>
        <ctrl:LabeledTextBox Grid.Column="2" Label="Channel of Trade:" Body="{Binding TradeChannel}" Margin="5,0,0,0"/>
     </Grid>

I have a list of objects, and I want to set DataContext of "SomeGrid" to First object in that list

SomeGrid.DataContex = list.First();

It works perfectly good if I put a TextBox control within this Grid, then Binding is working, bot for some reason User Control binding will not work. Am I doing it wrong?

PolarnyMis
  • 45
  • 5
  • In case Label and Body are properties of the UserControl, bind to them like `Text="{Binding Body, RelativeSource={RelativeSource AncestorType=UserControl}}"`. Make sure that the UserControl does not explicitly set its own DataContext. – Clemens Feb 11 '21 at 14:26
  • @Clemens thank you! Now it's working. – PolarnyMis Feb 11 '21 at 14:32

0 Answers0