0
我有關於依賴項屬性和數據綁定的非常基本的問題。我創建了一個簡單的類名TDTVm,它是我的ViewModel類。它有一個名爲IsShaftMovingUp的布爾依賴屬性,它的初始值是'False'我已經將此值綁定到UI上的一個文本框。現在我想在屏幕上顯示'IsShaftMovingUp'的實時值。WPF依賴屬性數據綁定
下面是我的虛擬機。
public class TDTVm : DependencyObject
{
public static DependencyProperty
ShaftMovingUpProperty = DependencyProperty.
Register("ShaftMovingUp", typeof(bool), typeof(TDTVm),
new PropertyMetadata(false, ShaftMovingUpChanged));
private static void ShaftMovingUpChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
Console.WriteLine("ok");
}
public bool IsShaftMovingUp
{
get
{
return (bool)GetValue(TDTVm.ShaftMovingUpProperty);
}
set
{
SetValue(TDTVm.ShaftMovingUpProperty, value);
}
}
}
下面是我的xamal代碼。
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Button Content="Button" HorizontalAlignment="Left" Margin="124,175,0,0" VerticalAlignment="Top" Width="74" Click="Button_Click"/>
<TextBox Text="{Binding IsShaftMovingUp,
UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Left" Height="22" Margin="96,244,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
</Grid>
</Window>
及以下的背後是我的代碼:
public partial class MainWindow : Window
{
TDTVm datacontext = new TDTVm();
public MainWindow()
{
InitializeComponent();
this.DataContext = datacontext;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
///Even after this line 'true' value is not getting updated on UI.
datacontext.IsShaftMovingUp = true;
}
}
當我點擊按鈕,我設置 'IsShaftMovingUp' 的值設置爲true。但仍然在UI上它沒有得到更新。 (我已經實現這個使用INotifyPropertyChanged的,但想嘗試同與依賴屬性,瞭解兩者之間的確切差)
感謝