使用WPF用户模型动态更新标签的content属性

时间:2014-07-02 00:04:31

标签: c# wpf binding

一个带有标签的简单WPF窗口:

<Window x:Name="MainWindow1" x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:A="clr-namespace:WpfApplication1"
        xmlns:System="clr-namespace:System;assembly=mscorlib"
        Title="MainWindow" Height="384" Width="669.114" Icon="alarmclock.ico" Closing="OnClosing" Loaded="OnLoaded" >
    <Grid x:Name="Grid1">
        <Label x:Name="Label1" Content="{Binding AlarmStatus}" HorizontalAlignment="Left" Margin="10,314,0,0" VerticalAlignment="Top"/>  
    </Grid>
</Window>

连接对象,以便可以将对象绑定到标签内容属性。是的我在窗口看到文字Off:

public class PropertyChangedBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        //Raise the PropertyChanged event on the UI Thread, with the relevant propertyName parameter:
        Application.Current.Dispatcher.BeginInvoke((Action)(() =>
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
        }));
    }
}

public class UserViewModel : PropertyChangedBase
{
    private string _alarmStatus = "Off";

    public string AlarmStatus
    {
        get { return _alarmStatus; }
        set
        {
            _alarmStatus = value;
            OnPropertyChanged("AlarmStatus"); //This is important!!!
        }
    }
}

/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window

我以为我可以像这样更改标签的值:

private void OnLoaded(object sender, RoutedEventArgs e)
{
    //Im setting a value but the UI does not change. The label still says Off
    UserViewModel aaaa = new UserViewModel();
    aaaa.AlarmStatus = "On";
}

1 个答案:

答案 0 :(得分:1)

您正在创建ViewModel的新实例,但View没有&#34;连接&#34;那个。

aaaa实例在OnLoaded()方法完成执行后立即死亡(超出范围并被取消引用),并在稍后进行垃圾收集。

您需要获取窗口当前正在使用的ViewModel的实际实例:

private void OnLoaded(object sender, RoutedEventArgs e)
{
    var viewModel = this.DataContext as UserViewModel;
    viewModel.AlarmStatus = "On";
}

我建议您阅读Rachel&#39; Article以更好地理解WPF中DataContext的概念。