【发布时间】:2016-07-27 09:30:15
【问题描述】:
我想知道是否可以在 Windows 之间共享数据上下文并且是 C#/WPF 中的 UserControl。
我有一个这样的主窗口(未完成):
MainWindow.xaml:
<Window x:Class="MyProject.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:MyProject"
xmlns:v="clr-namespace:MyProject.Views"
mc:Ignorable="d"
Title="MyProject" >
<Window.DataContext>
<local:MainViewModel/>
</Window.DataContext>
<Grid>
<v:GenerateView/>
<v:ReadView/>
</Grid>
</Window>
MainViewModel.cs:
public class MainViewModel : ViewModelBase
{
#region Properties
#endregion
#region Fields
#endregion
#region Constructor
public MainViewModel()
: base()
{
}
#endregion
#region Methods
#endregion
#region Commands
#endregion
}
根据未来的参数,我将显示我的视图 GenerateView 或 ReadView。实际上我正在开发 UserControl GenerateView,但我想知道我是否可以使用相同的 Datacontext。
根据that post,我是这样开始的:
<UserControl x:Class="MyProject.Views.GenerateView"
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:MyProject.Views"
xmlns:p="clr-namespace:MyProject.Properties"
xmlns:MyProject="clr-namespace:MyProject"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
DataContext="{Binding DataContext, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type MyProject:MainWindow}}}">
<Grid>
</Grid>
</UserControl>
但它不起作用,当我尝试访问GenerateView中的Datacontext时,它为空。
编辑:
我忘记了部分代码:
public partial class GenerateView : UserControl
{
private MainViewModel Context
{
get
{
return DataContext as MainViewModel;
}
}
public GenerateView()
{
InitializeComponent();
Context.PropertyChanged += Context_PropertyChanged;
}
private void Context_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
//Action to perform
}
}
Context.PropertyChanged += Context_PropertyChanged; 行抛出异常,因为 Datacontext 为空。
【问题讨论】:
-
如果没有明确设置,DataContext 会向下继承到所有子控件。尝试从您的 UserControls 中删除它并仅在 Window 中设置它。
-
另外,在调用构造函数之前不会设置 DataContext。使用 DataContextChanged 事件了解它的设置时间。
-
@Nudity 我从 UserControls 中删除了它,并进行了测试。 DataContext 在构造函数 GenerateView 上为 null,但在
MainViewModel中的InitializeComponent之后,DataContext 在两者上都是正确的。但我无法在我的 UserControl @Andrew Perfect 上设置Context.PropertyChanged!
标签: c# wpf datacontext