我正在NotifyOnSourceUpdated以下最小 WPF 應用程式中試驗該屬性:
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!");
}
}
}
有兩件事我在這里感到困惑:
- 當我單擊按鈕時,它
Content不會使用字串更新"changed" - 我附加到
myButton.SourceUpdated事件的處理程式沒有被觸發,我從來沒有收到訊息框。
為什么沒有發生上述兩種行為?我在這里想念什么?
uj5u.com熱心網友回復:
您需要指定系結路徑:
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事件就會發生,例如,當您在 data-bound 中鍵入內容時TextBox。你的例子中沒有提到它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/527043.html
標籤:C#wpf数据绑定
