wpf 未触发Button的SourceUpdated处理程序,并且对绑定源的更改未反映在Button内容中

k4emjkb1  于 2022-11-18  发布在  其他
关注(0)|答案(1)|浏览(177)

我正在以下最小WPF应用程序中试验NotifyOnSourceUpdated属性:
XAML文件:

<Window x:Class="notify_on_source_updated.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:notify_on_source_updated"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Button x:Name="myButton" Click="myButton_Click" />
</Window>

程式码后置:

namespace notify_on_source_updated
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public string SourceText {get; set;}
        
        public MainWindow()
        {
            InitializeComponent();
            SourceText = "test";
            Binding binding = new Binding();

            binding.Source = SourceText;
            binding.NotifyOnSourceUpdated=true;
            
            myButton.SourceUpdated += myButton_SourceUpdated;
            myButton.SetBinding(ContentControl.ContentProperty, binding);
        }

        private void myButton_Click(object sender, RoutedEventArgs e)
        {
            SourceText = "changed";
        }

        private void myButton_SourceUpdated(object sender, DataTransferEventArgs e)
        {
            MessageBox.Show("Updated!");
        }
    }
}

有两件事我很困惑:
1.当我单击按钮时,它的Content未更新为字符串"changed"
1.我附加到myButton.SourceUpdated事件的处理程序没有被触发,并且我从来没有得到消息框。
为什么上面的两种行为没有发生?我在这里遗漏了什么?

wsewodh2

wsewodh21#

您需要指定绑定路径:

public MainWindow()
{
    InitializeComponent();
    SourceText = "test";
    Binding binding = new Binding();

    binding.Path = new PropertyPath(nameof(SourceText));
    binding.Source = this;
    binding.NotifyOnSourceUpdated=true;

    // intList is the ListBox
    myButton.SourceUpdated += myButton_SourceUpdated;
    myButton.SetBinding(ContentControl.ContentProperty, binding);
}

然后,若要更新Button,您必须实作INotifyPropertyChanged界面,并引发数据系结来源属性的PropertyChanged事件:

public partial class MainWindow : Window, INotifyPropertyChanged
{
    private string _sourceText;
    public string SourceText
    {
        get { return _sourceText; }
        set 
        { 
            _sourceText = value; 
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(SourceText))); 
        }
    }

    public event PropertyChangedEventHandler? PropertyChanged;
    ...
}

另一个选项是显式更新绑定:

private void myButton_Click(object sender, RoutedEventArgs e)
{
    SourceText = "changed";
    myButton.GetBindingExpression(ContentControl.ContentProperty).UpdateTarget();
}

SourceUpdated事件发生在输入控件的值从绑定目标传输到绑定源时,例如,在数据绑定的TextBox中键入内容时。

相关问题