C#、WPF 绑定、MVVM、INotifyPropertyChanged、尝试绑定实例属性但未成功

C#, WPF Binding, MVVM, INotifyPropertyChanged, Trying to bind instance properties without success

有没有办法将 class 的实例放入另一个 class,然后使用 INotifyPropertyChanged 从它们更新 UI?例如,WhiteJack class 中的这些 PlayerBaseClass 实例 PlayerOne 和 PlayerTwo,并在 UI 中更新了它们?唯一可行的解​​决方案是将上下文直接设置为玩家的实例,然后将它们提供给作为主视图模型的视图模型..!

   class MultipleDataContexts
    {
        public WhiteJack WhiteJackViewModel { get; set; }
        public PlayerBaseClass PlayerOne { get; set; }
        public PlayerBaseClass PlayerTwo { get; set; }
        public MultipleDataContexts()
        {
            PlayerOne = new PlayerBaseClass();
            PlayerTwo = new PlayerBaseClass();
            WhiteJackViewModel = new WhiteJack(PlayerOne, PlayerTwo);
        }
    }
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            this.DataContext = new MultipleDataContexts(); // set datacontext for the INotifyPropertyChanged
            InitializeComponent();
            this.WindowState = WindowState.Maximized; //Window to the max.
        }
}

我猜这是唯一可行的方法。视图必须直接查看设置的上下文,它不能查看其成员。我对吗?因为这不起作用:

this.DataContext = new WhiteJack();

是的,没有。我无法通过将文本块绑定到 WhiteJack 中的实例来更新 UI,无论我是否将上下文设置为命名实例。

您正在为此(Window)将 DataContext 设置为 WhiteJack() 的新实例。我仍然不确定您的最终目标是什么,但是在您的 MultipleDataContexts class 中实例化您的两个 PlayerBaseClass 对象将允许您使用您创建的属性设置背景。所以在你的 ViewModel 中设置你的颜色:

型号

class MultipleDataContexts
{
    public PlayerBaseClass PlayerOne { get; set; }
    public PlayerBaseClass PlayerTwo { get; set; }
    public MultipleDataContexts()
    {
        PlayerOne = new PlayerBaseClass();
        PlayerTwo = new PlayerBaseClass();
    }
}

视图模型

        MultipleDataContexts mdc = new MultipleDataContexts();
        mdc.PlayerOne.TextBlock_Background = new SolidColorBrush(Colors.Red);
        mdc.PlayerTwo.TextBlock_Background = new SolidColorBrush(Colors.Black);
        this.DataContext = mdc;

XAML

    <TextBlock x:Name="SeatOne_TextBlock" HorizontalAlignment="Left" Text="text" Background="{Binding PlayerOne.TextBlock_Background}" VerticalAlignment="Top"  Opacity="1" Height="155" Width="105" FontFamily="Courier New" Padding="0" Margin="0" />
    <TextBlock x:Name="SeatTwo_TextBlock" HorizontalAlignment="Left" Text="text" Background="{Binding PlayerTwo.TextBlock_Background}" VerticalAlignment="Top"  Opacity="1" Height="155" Width="105" FontFamily="Courier New" Padding="0" Margin="0" />

设置这些属性并将 MultipleDataContexts class 绑定到我的 Window 给我一个红色和黑色的文本块背景。