Cri*_*ris 11 wpf datacontext user-controls
我需要从我在WPF中创建的UserControl(包含文本框和列表框的网格:我需要在此列表框中插入项目)访问容器的DataContext:这是最好的方法吗?我想将DataContext作为参数传递给用户控件,但认为有一种更简洁的方法
提前致谢 !
我有时会嵌套用户控件,而孙用户控件有时需要祖父母视图的数据上下文.到目前为止我找到的最简单的方法(我有点新手)是使用以下内容:
<Shared:GranchildControl DataContext="{Binding RelativeSource={RelativeSource
FindAncestor, AncestorType={x:Type GrandparentView}},
Path=DataContext.GrandparentViewModel}" />
Run Code Online (Sandbox Code Playgroud)
小智 5
将此 BindingProxy 类添加到您的项目中:
using System.Windows;
namespace YourNameSpace
{
/// <summary>
/// Add Proxy <ut:BindingProxy x:Key="Proxy" Data="{Binding}" /> to Resources
/// Bind like <Element Property="{Binding Data.MyValue, Source={StaticResource Proxy}}" />
/// </summary>
public class BindingProxy : Freezable
{
protected override Freezable CreateInstanceCore()
{
return new BindingProxy();
}
public object Data
{
get { return (object)GetValue(DataProperty); }
set { SetValue(DataProperty, value); }
}
public static readonly DependencyProperty DataProperty = DependencyProperty.Register("Data", typeof(object), typeof(BindingProxy));
}
}
Run Code Online (Sandbox Code Playgroud)
Data="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}},Path=DataContext}"如果您需要更复杂的东西,您可以使用自定义转换器。现在您可以访问该父级的 DataContext: {Binding Data.MyCommand, Source={StaticResource BindingProxy}}
<UserControl
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:common="clr-namespace:YourNameSpace;assembly=YourAssembly"
mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300">
<UserControl.Resources>
<common:BindingProxy x:Key="BindingProxy" Data="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}},Path=DataContext}" />
</UserControl.Resources>
<Border>
<Button Command="{Binding Data.MyCommand, Source={StaticResource BindingProxy}}">Execute My Command</Button>
<!-- some visual stuff -->
</Border>
</UserControl>
Run Code Online (Sandbox Code Playgroud)