不在构造函数中设置viewmodel的Datacontext

时间:2016-12-15 15:29:45

标签: c# wpf mvvm mahapps.metro

我有一个使用WPF的{​​{1}}申请,我有一个mah metro

tab control

我在 <Controls:MetroAnimatedTabControl Grid.Column="3" Grid.Row="1" SelectedIndex="{Binding SelectedTabIndex,Mode=TwoWay}"> <TabItem Header="Manual Control"> <view:ManualControlView DataContext="{Binding ManualControlViewModel}"/> </TabItem> <TabItem Header="Set up"> <view:SetupView DataContext="{Binding SetupViewModel}"/> </TabItem> </Controls:MetroAnimatedTabControl> 中设置了datacontext。我正在创建TabItem并将该引用传递给每个TcpCllient。当我在构造函数中执行此操作时,一切正常。

ViewModel

但是,我不想在构造函数中创建 public MainViewModel() { _client = new TcpClient(IP_ADDRESS, PORT); _client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true); _master = ModbusIpMaster.CreateIp(_client); ManualControlViewModel = new ManualControlViewModel(_master); SetupViewModel = new SetupViewModel(_master); } 。相反,当我点击&#34; Connect&#34;我窗口中的按钮。但是,当我点击我的&#34; Connect&#34;按钮执行TcpClient方法执行此操作我的观点未设置为OnConnect

datacontext

有可能实现这个目标吗?

1 个答案:

答案 0 :(得分:1)

更新ViewModel的属性时,应通知Control属性已更改。

        public class ViewModel : INotifyPropertyChanged
        {

            public SetupViewModel SetupViewModel 
            {
                get { return m_SetupViewModel; }
                set
                {
                    m_SetupViewModel = value;
                    OnPropertyChanged();
                }
            }

            public ManualControlViewModel ManualControlViewModel
            {
                get { return m_ManualControlViewModel; }
                set
                {
                    m_ManualControlViewModel = value;
                    OnPropertyChanged();
                }
            }

            public event PropertyChangedEventHandler PropertyChanged;

            private void OnConnect(object obj)
            {
                _client = new TcpClient(IP_ADDRESS, PORT);
                _client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
                _master = ModbusIpMaster.CreateIp(_client);
                Connected = _client.Connected;

                ManualControlViewModel = new ManualControlViewModel(_master);
                SetupViewModel = new SetupViewModel(_master);

                StartReadingInfo();
            }

            private void OnPropertyChanged([CallerMemberName] string PropertyName = "")
            {
                var handler = PropertyChanged;
                if (handler != null) handler(this, new PropertyChangedEventArgs(PropertyName));
            }

            private ManualControlViewModel m_ManualControlViewModel;
            private SetupViewModel m_SetupViewModel;
        }