如何在 XAML 中将数据上下文设置为用户控件的类
本文关键字:设置 用户 控件 上下文 数据 XAML | 更新日期: 2023-09-27 18:34:28
我有以下实现 INotifyPropertyChanged 的类
更新通知.cs
public class updateNotify : INotifyPropertyChanged
{
private DateTime? previousUpdate;
private DateTime? nextUpdate;
public event PropertyChangedEventHandler PropertyChanged;
public updateNotify()
{
}
public updateNotify(DateTime? value)
{
this.previousUpdate = value;
}
public DateTime? GASpreviousUpdate
{
get { return previousUpdate; }
set
{
previousUpdate = value;
// Call OnPropertyChanged whenever the property is updated
OnPropertyChanged("GASpreviousUpdate");
}
}
public DateTime? GASnextUpdate
{
get { return nextUpdate; }
set
{
nextUpdate = value;
// Call OnPropertyChanged whenever the property is updated
OnPropertyChanged("GASnextUpdate");
}
}
// Create the OnPropertyChanged method to raise the event
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
MainWindow.xaml.cs
public partial class MainWindow
{
private updateNotify properties = new updateNotify();
'''
public void start_dispatcherTimer()
{
dispatcherTimer.Stop();
DateTime timeNow = DateTime.Now;
properties.GASpreviousUpdate = timeNow;
properties.GASnextUpdate = timeNow.AddMinutes((double)Properties.Settings.Default.GASInterval);
dispatcherTimer.Start();
}
}
然后在 XAML 中
<UserControl x:Class="ProjectXYZ.Content.MainData"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d" d:DesignWidth="300" Height="400" >
....
<StackPanel>
<Label Content="Previous Refresh" Target="{Binding ElementName=PreviousRefresh}"/>
<TextBox x:Name="PreviousRefresh" Width="140" Text="{Binding Path=GASpreviousUpdate, Mode=OneWay}"/>
</StackPanel>
<StackPanel>
<Label Content="Next Refresh" Target="{Binding ElementName=NextRefresh}"/>
<TextBox x:Name="NextRefresh" Width="140" Text="{Binding Path=GASnextUpdate, Mode=OneWay}"/>
</StackPanel>
</UserControl>
但文本框不会在 UI 中更新以进行Text="{Binding Path=GASpreviousUpdate, Mode=OneWay}"
和Text="{Binding Path=GASnextUpdate, Mode=OneWay}"
我想我需要设置数据上下文,但不确定如何在用户控件 XAML 中执行此操作。请问有人可以指出我正确的方向吗?
尝试:
public partial class MainWindow
{
public MainWindow()
{
this.DataContext = this.properties; // <----
}
}
我不会称该领域为properties