R
R
Rinsewind2018-08-13 11:33:34
WPF
Rinsewind, 2018-08-13 11:33:34

C# WPF usercontroll Why doesn't binding work?

Good afternoon! There is the following code:

<UserControl x:Name="MarketItemContrl" x:Class="WpfApp2.MarketItemControl"
             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:WpfApp2"
             mc:Ignorable="d" 
             d:DesignHeight="100" d:DesignWidth="100">
    <Grid>
        <TextBlock HorizontalAlignment="Left" Margin="10,10,0,0" TextWrapping="Wrap" Name="tb1" Text="{Binding ElementName=MarketItemContrl, Path=Data.name}" VerticalAlignment="Top" Width="80" Height="80"/>

    </Grid>
</UserControl>

namespace WpfApp2
{
    public partial class MarketItemControl : UserControl
    {
        public MarketItemControl()
        {
            InitializeComponent();
            Data = new MarketItem();
            Data.name = "Test val";
            DataContext = Data;
        }
        public MarketItem Data { get; set; }
    }
}

How can I get the binding to work? Data.name is a string.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
LiptonOlolo, 2018-08-13
@LiptonOlolo

Add DataContext before InitializeComponent();
Text="{Binding name}"

D
Dmitry Bashinsky, 2018-08-13
@BashkaMen

In your case DataContext = Data;
which means that it is enough to do this: And here is the best way to do it: In the constructor of the control, write
<TextBlock Text="{Binding Data.name}"/>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question