WPF DataBinding for Standard Encoding CLR Properties

Just learn WPF data binding and have a space in my understanding. I saw several similar questions in StackOverflow, but I'm still trying to determine what I did wrong.

I have a simple Person class with the Firstname and Surname property (standard CLR properties). I also have a standard CLR property in my Window class that provides an instance of Person.

I have XAML with two binding methods. The first works, the second - no. Can someone help me understand why the second method fails? There is no communication error message in the output log.

<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication1"
    Title="Window1" Height="300" Width="300"
    DataContext="{Binding RelativeSource={RelativeSource Self}, Path=MyPerson}">
<StackPanel>
    <Label>My Person</Label>
    <WrapPanel>
        <Label>First Name:</Label>
        <Label Content="{Binding RelativeSource={RelativeSource AncestorType=Window, Mode=FindAncestor}, Path=MyPerson.FirstName}"></Label>
    </WrapPanel>
    <WrapPanel>
        <Label>Last Name:</Label>
        <Label Content="{Binding MyPerson.Surname}"></Label>
    </WrapPanel>
</StackPanel>

Edit: Good, thanks. I changed the second expression to:

<Label Content="{Binding Surname}"></Label>

I still can't get it to work!

+3
4

, . WPF, , .

MyPerson InitializeComponent.

, , , MyPerson .

, MyPerson , DataContext.

, , !

+2

<Label Content="{Binding Surname}"/>

DataContext .

datacontext , , , . - :

<Window.Resources>
    <local:BindingClass x:Key="bindingClass"/>
</Window.Resources>
<Grid DataContext="{StaticResource bindingClass.MyPerson}">
    <Label Content="{Binding Surname}"/>
</Grid>

, ( BindingClass), MyPerson.

, , xaml.

+1

-, , . , , , DataContext MyPerson. DataContext, , , Surname. , , MyPerson.MyPerson.Surname.

+1

Another easy way to handle this first binding is to give your window a name and specify it ElementNamein the binding:

<Window x:Class="WpfApplication1.Window1"
    Name="MyWindow"
    ...>
<StackPanel>
    <Label>My Person</Label>
    <WrapPanel>
        <Label>First Name:</Label>
        <Label Content="{Binding Path=MyPerson.FirstName, ElementName=MyWindow}"></Label>
    </WrapPanel>
    <WrapPanel>
        <Label>Last Name:</Label>
        <Label Content="{Binding MyPerson.Surname}"></Label>
    </WrapPanel>
</StackPanel>
0
source

Source: https://habr.com/ru/post/1747521/


All Articles