【问题标题】:How to bind the DataContext of the Window or its child to one specific property of the Window?如何将 Window 或其子的 DataContext 绑定到 Window 的一个特定属性?
【发布时间】:2015-02-02 07:51:11
【问题描述】:

有点愚蠢的问题,但不知何故我找不到如何将Window 或其ContentDataContext (例如Grid 面板)绑定到Window 的一个特定属性(比如说,ViewModel 在下面的示例中):

代码:

internal partial class MyWin : Window
{
    public MyViewModelType ViewModel { get; set; }
    ...
}

XAML:

<Window x:Class="MyNs.MyWin"
        ...
        DataContext="{Binding RelativeSource={RelativeSource Self}}" />

    <Grid DataContext={Binding ViewModel}> <!-- doesn't work??? -->
        ...
    </Grid>
</Window>

【问题讨论】:

  • ViewModel 属性会引发INPC.PropertyChanged 事件吗?如果不是什么时候换?是在InitializeComponent()之后吗?

标签: c# wpf xaml binding datacontext


【解决方案1】:

请为视图模型定义字段,因为它不会改变并实现 INPC

 private MyViewModelType viewmodel;

    public MyViewModelType ViewModel
    {
        get 
        { 
            if(viewmodel == null)
            {
                viewmodel = new MyViewModelType();
            }
            return viewmodel; 
        }
        set 
        { 
            viewmodel = value; 
            OnPropertyChanged("ViewModel")
        }
    }

其余代码保持不变。

【讨论】:

    【解决方案2】:

    我认为你的方法是错误的

    如果您的窗口进行了连接,它会正常工作

    public partial class MyWindow
    {
        public MyWindow()
        {
            InitializeComponent();
            DataContext = ViewModel = new MyViewModelType();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-26
      • 1970-01-01
      • 1970-01-01
      • 2018-12-08
      • 1970-01-01
      • 2012-03-27
      相关资源
      最近更新 更多