Wpf Binding Problem

I have a rectangle with a tooltip in my window. Pressing a button involves changing the text of the tooltip, but it is not.

XAML:

 <Grid>
    <Grid.RowDefinitions>
        <RowDefinition />
        <RowDefinition />
    </Grid.RowDefinitions>

    <Grid.Resources>
        <ToolTip x:Key="@tooltip">
            <TextBlock Text="{Binding Name}" />
        </ToolTip>
    </Grid.Resources>

    <Rectangle Width="200" Height="200" Fill="LightBlue" VerticalAlignment="Center" HorizontalAlignment="Center"
            ToolTip="{DynamicResource @tooltip}" />
    <Button Click="Button_Click" Grid.Row="1" Margin="20">Click Me</Button>
</Grid>

code behind:

public partial class Window1 : Window
{

    public Window1()
    {
        DataContext = new Person { Name = "A" };
        InitializeComponent();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        DataContext = new Person { Name = "B" };
    }
}
+3
source share
2 answers

Change binding to:

Example:

<ToolTip x:Key="@tooltip">
    <TextBlock Text="{Binding RelativeSource={RelativeSource Mode=Self}, Path=Parent.PlacementTarget.DataContext.Name}" />
</ToolTip>

Cause:

The reason this works, and yours does not, is because the element TextBlocknever receives a notification about a property change with the name Namethat you associate in your code.

, TextBlock Parent (ToolTip) > PlacementTarget (Button) > DataContext (Person) > Name. TextBlock PlacementTarget, Button. Button TextBlock DataContext , , TextBlock .

+3

, , . -, . , . , .

Person

 public class Person:INotifyPropertyChanged
{
    private string name;

    public string Name
    {
        get { return name; }
        set { name = value; OnPropertyChanged("Name"); }
    }



    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;
    public void OnPropertyChanged(string name)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(name));
        }
    }
    #endregion
}

person datacontext. ,

public Window1()
    {
        MyPerson = new Person();
        MyPerson.Name = "A";
        DataContext = MyPerson;
        InitializeComponent();
    }

    private Person myPerson;

    public Person MyPerson
    {
        get { return myPerson; }
        set { myPerson = value; OnPropertyChanged("MyPerson"); }
    }
    private void Button_Click(object sender, RoutedEventArgs e)
    {
        MyPerson.Name = "B";
    }

, ...

0

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


All Articles