我有一个对象,不能继承DependencyObject或使用NotifyPropertyChanged,并且我已经将其绑定到相当多的控件上,所以当属性更改时,我不想在代码中去每个控件并更改它的值。因此,我认为必须有一种方法可以告诉XAML用一两行代码“重新绑定”所有已绑定的内容,而不是一个一个地去处理:
label1.Content = myObject.DontNotifyThis;
label2.Content = myObject.DontNotifyThisEither;
label3.Content = myObject.DontEvenThinkOfNotifyingThis;
label4.Content = myObject.NotSoFastPal;
如此等等...
这是一个过于简化的例子:
XAML:
<Window x:Class="StackOverflowTests.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" x:Name="window1" Height="300" Width="300" Loaded="window1_Loaded">
<Grid x:Name="gridMain">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Label Grid.Row="0" Content="{Binding Status}" ContentStringFormat="Today's weather: {0}" />
<Label Grid.Row="2" Content="{Binding Temperature}" ContentStringFormat="Today's temperature: {0}" />
<Label Grid.Row="1" Content="{Binding Humidity}" ContentStringFormat="Today's humidity: {0}" />
</Grid>
</Window>
C#:
using System.Windows;
namespace StackOverflowTests
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
Weather weather = new Weather("Cloudy", "60F", "25%");
public Window1()
{
InitializeComponent();
this.DataContext = weather;
}
private void window1_Loaded(object sender, RoutedEventArgs e)
{
weather.Status = "Sunny";
weather.Temperature = "80F";
weather.Humidity = "3%";
}
}
class Weather
{
public string Status { get; set; }
public string Temperature { get; set; }
public string Humidity { get; set; }
public Weather(string status, string temperature, string humidity)
{
this.Status = status;
this.Temperature = temperature;
this.Humidity = humidity;
}
}
}
我找到了一种方法,但并不十分优雅,不幸的是,我不能只将DataContext设置为weather的新实例,它需要是相同的引用(这就是为什么我将其设置为null以进行更改的原因):
private void window1_Loaded(object sender, RoutedEventArgs e)
{
weather.Status = "Sunny";
weather.Temperature = "80F";
weather.Humidity = "3%";
// bad way to do it
Weather w = (Weather)this.DataContext;
this.DataContext = null;
this.DataContext = w;
}
提前致谢!