我想要一個 INotifyPropertyChanged 測驗。以下代碼運行良好。但我想用 xaml-binding 替換 cs-code-binding。問題是如何在不影響程式功能的情況下做到這一點。感謝幫助!
XAML:
<StackPanel Margin="5">
<TextBox x:Name="textBox" Margin="5"/>
<CheckBox x:Name="checkBox" Margin="5" HorizontalAlignment="Center"/>
<Button x:Name="button" Margin="5" Content="UpdateTime" Click="button_Click"/>
</StackPanel>
代碼隱藏:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
BindingOperations.SetBinding(this.textBox, TextBox.TextProperty, new Binding("TimeNow") { Source = clock });
}
Clock clock = new Clock();
private void button_Click(object sender, RoutedEventArgs e)
{
if ((bool)checkBox.IsChecked) clock.TimeNow = DateTime.Now;
}
}
class Clock : INotifyPropertyChanged
{
private DateTime dateTime;
public DateTime TimeNow
{
get { return dateTime; }
set { dateTime = value; OnPropertyChanged(); }
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
uj5u.com熱心網友回復:
將DataContextMainWindow 的屬性設定為 Clock 實體
public MainWindow()
{
InitializeComponent();
DataContext = clock;
}
并在 XAML 中宣告一個使用當前 DataContext 作為源物件的系結:
<TextBox Text="{Binding TimeNow}"/>
作為在代碼中創建 Clock 成員的替代方法,您可以在 XAML 中分配 DataContext
<Window.DataContext>
<local:Clock />
</Window.DataContext>
并在后面的代碼中訪問 Clock 物件,如下所示:
((Clock)DataContext).TimeNow = DateTime.Now;
uj5u.com熱心網友回復:
使用 nuget 包ReactiveUI.Fody,ReactiveUI.WPF您可以撰寫 ViewModel
public class MainViewModel : ReactiveObject
{
public MainViewModel()
{
var canUpdateTime = this.WhenAnyValue(e => e.MayUpdateTime);
UpdateTimeCommand = ReactiveCommand.Create(() => TimeNow = DateTime.Now, canUpdateTime);
}
[Reactive] public bool MayUpdateTime { get; set; }
[Reactive] public DateTime TimeNow { get; set; }
public ReactiveCommand<Unit, DateTime> UpdateTimeCommand { get; }
}
和視圖
<Window
x:Class="ReactiveWpfApp5.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:local="clr-namespace:ReactiveWpfApp5"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:viewModels="clr-namespace:ReactiveWpfApp5.ViewModels"
Title="MainWindow"
Width="800"
Height="450"
mc:Ignorable="d">
<Window.DataContext>
<viewModels:MainViewModel />
</Window.DataContext>
<DockPanel>
<StackPanel>
<TextBox Text="{Binding TimeNow, Mode=TwoWay}" />
<CheckBox Content="May Update Time" IsChecked="{Binding MayUpdateTime}" />
<Button Command="{Binding UpdateTimeCommand}" Content="Update Time" />
</StackPanel>
</DockPanel>
</Window>
就這些
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/429087.html
