如何使用RelativeSourceWPF绑定以及不同的用例?
我在应用游戏中获得了2个面板
它们都受到不同元素的束缚.
GameDetailsPanel.DataContext = game ;
GameBoardPanel.DataContext = gameBoard ;
Run Code Online (Sandbox Code Playgroud)
*游戏有Turn Property*.
public Class Game
{
public bool Turn{ get; set;}
}
Run Code Online (Sandbox Code Playgroud)
现在我需要将GameBoardPanel中的一个绑定到Property Turn的值,
*例如:类似*的东西
<Button Fill={Binding Source=GameDetailsPanel.DataContext , Path=Turn } ></Button>
Run Code Online (Sandbox Code Playgroud)
我如何在绑定中引用GameDetailsPanel.DataContext?
我一直在玩 WPF 和 MVVM 并注意到一件奇怪的事情。在{Binding ElementName=...}自定义用户控件上使用时,用户控件中根元素的名称似乎在使用该控件的窗口中可见。说,这是一个示例用户控件:
<UserControl x:Class="TryWPF.EmployeeControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TryWPF"
Name="root">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Text="{Binding}"/>
<Button Grid.Column="1" Content="Delete"
Command="{Binding DeleteEmployee, ElementName=root}"
CommandParameter="{Binding}"/>
</Grid>
</UserControl>
Run Code Online (Sandbox Code Playgroud)
对我来说看起来很合法。现在,依赖属性DeleteEmployee在代码隐藏中定义,如下所示:
public partial class EmployeeControl : UserControl
{
public static DependencyProperty DeleteEmployeeProperty
= DependencyProperty.Register("DeleteEmployee",
typeof(ICommand),
typeof(EmployeeControl));
public EmployeeControl()
{
InitializeComponent();
}
public ICommand DeleteEmployee
{
get
{
return (ICommand)GetValue(DeleteEmployeeProperty);
}
set
{
SetValue(DeleteEmployeeProperty, value);
}
}
}
Run Code Online (Sandbox Code Playgroud)
这里没有什么神秘的。然后,使用控件的窗口如下所示:
<Window x:Class="TryWPF.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TryWPF" …Run Code Online (Sandbox Code Playgroud) 我正在使用Silverlight 4.我有ItemsControl一个自定义DataTemplate.从那以后DataTemplate,我想绑定到UserControl's中的某些东西DataContext- 而不是DataContextitem控件中的特定元素.有没有办法做到这一点?
假设我有这个 ViewModel 和 xaml:
class MyViewModel
{
public MyStringValue {get;set;} = "HelloWorld"
public IList<CustomObject> ChildViewModels{get;set;}
}
<DataTemplate DataType="{x:Type local:MyViewModel}">
<ItemsControl ItemsSource="{Binding ChildViewModels}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<TextBlock Text="{Binding Path=MyStringValue,
RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType={x:Type local:MyViewModel}}}"/>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</DataTemplate>
Run Code Online (Sandbox Code Playgroud)
我不断收到此错误消息:“无法找到使用引用 'RelativeSource FindAncestor ... 进行绑定的源...” 所以基本上,我正在尝试绑定 ItemsControl 的父属性容器,但似乎我不能。