簡體   English   中英

C#,WPF綁定,MVVM,INotifyPropertyChanged,嘗試綁定實例屬性但未成功

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

有沒有一種方法可以將一個類的實例放置在另一個類中,然后使用INotifyPropertyChanged從它們中更新UI? 例如,WhiteJack類中的這些PlayerBaseClass實例PlayerOne和PlayerTwo,並在用戶界面中對其進行了更新嗎? 唯一有效的解決方案是將上下文直接設置為播放器的實例,然后將它們輸入到作為主要視圖模型的視圖模型中。

   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。

您正在為此(窗口)將DataContext設置為WhiteJack()的新實例。 我仍然不確定您的最終目標是什么,但是在MultipleDataContexts類中實例化兩個PlayerBaseClass對象將允許您使用創建的屬性來設置Background。 因此,在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類綁定到我的Window,可以得到紅色和黑色的文本塊背景。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM