我们创建了一个自定义 ComboBox 控件,它有一个按钮来清除 ComboBox 的选择:
<Style TargetType="{x:Type local:ClearableComboBox}">
<Setter Property="SelectedItem" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:ClearableComboBox}">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<DockPanel>
<Button Name="btnClear" DockPanel.Dock="Right" ToolTip="Clear" Width="20">
<Image Source="pack://application:,,,/img/icons/silk/cross.png" Stretch="None" />
</Button>
<ComboBox Name="comboBox"
ItemsSource="{TemplateBinding ItemsSource}"
SelectedItem="{TemplateBinding SelectedItem}"
DisplayMemberPath="{TemplateBinding DisplayMemberPath}" />
</DockPanel>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
Run Code Online (Sandbox Code Playgroud)
ItemsSource 的绑定工作正常,但是 SelectedItem 的绑定没有。在谷歌搜索后,我在这里找到了问题的解决方案。具体来说,将 SelectedItem 绑定更改为
SelectedItem="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=SelectedItem}"
使其按预期工作。
为什么 SelectedItem 上的原始 TemplateBinding 不起作用,而 ItemsSource 的 TemplateBinding 工作得很好?
我在Window的Resources部分中有一个DataTemplate,它创建一个带有ContextMenu的TextBlock.我希望能够设置ContextMenu中的MenuItem是否可以从我的Window视图模型中看到.我尝试通过设置访问Window的DataContext ElementName,并尝试设置RelativeSource,但这两种方法都导致了绑定错误.我不确定我还能尝试什么.
我创建了一个小例子来展示我正在尝试做的事情:
XAML:
<Window x:Class="DataTemplateTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<ResourceDictionary>
<DataTemplate x:Key="TestDataTemplate">
<TextBlock Text="{Binding}">
<TextBlock.ContextMenu>
<ContextMenu>
<MenuItem Header="Test" Visibility="{Binding Path=DataContext.MenuItemVisible, ElementName=Root}"/>
</ContextMenu>
</TextBlock.ContextMenu>
</TextBlock>
</DataTemplate>
</ResourceDictionary>
</Window.Resources>
<ScrollViewer x:Name="Root">
<ItemsControl ItemsSource="{Binding Path=Items}" ItemTemplate="{StaticResource TestDataTemplate}" />
</ScrollViewer>
Run Code Online (Sandbox Code Playgroud)
代码背后:
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows;
namespace DataTemplateTest
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
protected readonly MainWindowViewModel vm;
public MainWindow()
{
InitializeComponent();
vm = new MainWindowViewModel(); …Run Code Online (Sandbox Code Playgroud)