我附上了一些WPF C#綁定代碼 - 爲什麼這個簡單的例子不工作? (只是想了解綁定到自定義對象)。這是當點擊按鈕增加模型中的計數器時,標籤不會更新。WPF C#綁定代碼 - 爲什麼這個簡單的例子不工作?
<Window x:Class="testapp1.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 Height="23" HorizontalAlignment="Left" Margin="20,12,0,0"
Name="testButton" VerticalAlignment="Top" Width="126"
Click="testButton_Click" Content="Increase Counter" />
<Label Content="{Binding Path=TestCounter}" Height="37"
HorizontalAlignment="Right" Margin="0,12,122,0"
Name="testLabel2" VerticalAlignment="Top"
BorderThickness="3" MinWidth="200" />
</Grid>
</Window>
namespace testapp1
{
public partial class MainWindow : Window
{
public TestModel _model;
public MainWindow()
{
InitializeComponent();
InitializeComponent();
_model = new TestModel();
_model.TestCounter = 0;
this.DataContext = _model;
}
private void testButton_Click(object sender, RoutedEventArgs e)
{
_model.TestCounter = _model.TestCounter + 1;
Debug.WriteLine("TestCounter = " + _model.TestCounter);
}
}
public class TestModel : DependencyObject
{
public int TestCounter { get; set; }
}
}
感謝
謝謝 - 現在就試試這個 - 所以你永遠不能直接綁定到一個普通的舊類對象,然後在WPF中? – Greg 2010-09-08 06:01:39
如果您實現INotifyPropertyChanged – Daniel 2010-09-08 06:02:29
,那麼您可以不,完全沒有 - 只要您通知目標(例如Textbox上的TextProperty)任何更改,就可以綁定到任何POCO對象的任何屬性。 DependenyProperties爲您完成這項工作,但您也可以在TestModel類上實現INotifyPropertyChanged(根據@ rudigrobler建議)並手動引發更改事件... – kiwipom 2010-09-08 06:04:32