WPF-MVVM-UserControl绑定

时间:2019-03-18 10:36:02

标签: c# wpf mvvm user-controls

我试图实现一个简单的UserControl示例,在TextBox中显示当前的DateTime,每秒更新四次。

我创建了一个简单的用户控件:

Dispose

其ViewModel在哪里:

<UserControl x:Class="UC.TestUC"
             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" 
             xmlns:local="clr-namespace:UC"
             mc:Ignorable="d" 
             d:DesignHeight="50" d:DesignWidth="100">
    <d:UserControl.DataContext>
        <local:TestUC_VM/>
    </d:UserControl.DataContext>
    <Grid Background="Azure">
        <TextBox Text="{Binding TestString}"/>
    </Grid>
</UserControl>

MainWindow XAML:

namespace UC
{
    public class TestUC_VM : INotifyPropertyChanged
    {
        private string _testString;
        public string TestString
        {
            get => _testString;
            set
            {
                if (value == _testString) return;
                _testString = value;
                OnPropertyChanged();
            }
        }

        public TestUC_VM()
        {
            TestString = "Test string.";
        }

        public event PropertyChangedEventHandler PropertyChanged;
        void OnPropertyChanged([CallerMemberName] string propertyName = null) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

及其ViewModel:

<Window x:Class="UC.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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:UC"
        mc:Ignorable="d"
        Title="MainWindow" Height="100" Width="200">
    <Window.DataContext>
        <local:MainWindow_VM/>
    </Window.DataContext>
    <Window.Resources>
        <local:TestUC_VM x:Key="TestUC_VM"/>
    </Window.Resources>
    <Grid>
        <local:TestUC DataContext="{StaticResource TestUC_VM}"/>
    </Grid>
</Window>

即使我在调试器中看到我正在通过TestString setter,也不会更新MainWindow。 我很确定在MainWindow中设置UC的DataContext时会遗漏一些琐碎的事情,但是经过数小时的浏览和思考,我还是找不到。

任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:1)

表达式

<local:TestUC DataContext="{StaticResource TestUC_VM}"/>

将TestUC_VM资源的值分配给UserControl的DataContext。这是与主视图模型的_uc_VM成员不同的对象,您稍后将对其进行更新。

将成员变成公共财产

public TestUC_VM UcVm { get; } = new TestUC_VM();

然后写

<local:TestUC DataContext="{Binding UcVm}"/>

像这样更新视图模型:

UcVm.TestString = ...