【发布时间】:2015-06-03 19:23:24
【问题描述】:
我编写了我的自定义控件SearchTextBox。此控件具有属性PopupContent。 PopupContent 有一个 CheckBox,我想将它绑定到属性 IsChecked 但绑定不起作用。我怎样才能正确地做到这一点?
<UserControl x:Class="TestEnv2.PanelViews.SolutionView.SolutionViewContent">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="25"/>
<RowDefinition Height="2"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Border Grid.Row="0" x:Name="SearchPanel" Visibility="Hidden" Background="#efeff2" >
<ctrl:SearchTextBox x:Name="SearchControl" Height="21" BorderThickness="0" VerticalContentAlignment="Center" Background="White"
SearchMode="Delayed" LabelText="Search Solution Explorer" Search="SolutionView_Search">
<ctrl:SearchTextBox.PopupContent>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="25"/>
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Margin="5,0,0,0" Text="Search options" Foreground="Gray" VerticalAlignment="Center"/>
<CheckBox Grid.Row="1" Margin="5,0,0,5" Content="Match case"
IsChecked="{Binding Path=SearchMatchCase, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type panels_soln:SolutionViewContent}}}"/>
</Grid>
</ctrl:SearchTextBox.PopupContent>
</ctrl:SearchTextBox>
</Border>
</Grid>
</UserControl>
后面的代码:
public partial class SolutionViewContent : UserControl
{
public static readonly DependencyProperty SearchMatchCaseProperty = DependencyProperty.
Register("SearchMatchCase", typeof(Boolean), typeof(SolutionViewContent), new UIPropertyMetadata(true));
public Boolean SearchMatchCase
{
get { return (Boolean)GetValue(SearchMatchCaseProperty); }
set
{
MessageBox.Show("SearchMatchCase");
SetValue(SearchMatchCaseProperty, value);
}
}
public SolutionViewContent()
{
InitializeComponent();
}
}
【问题讨论】:
-
给你的 UserControl 一个 x:Name="root" 然后 {Binding whatever, ElementName=root}
-
当您说您的绑定不起作用时,您能澄清一下您的意思吗?我将您的代码复制/粘贴到示例 WPF 项目中,绑定对我来说很好。我最好的猜测是您的
PopupContent属性与大多数控件在视觉树的不同层上工作,因此它没有与其他所有控件相同的 UI 树来遍历。您可以使用Snoop 之类的工具来验证可视化树是否符合您的预期,并且 CheckBox 位于 SolutionViewContext 可视化树中的某个位置。 -
欢迎来到 Stack Overflow!我用你的问题解决了一些语法问题。您可能会考虑将问题标题更改为更具体一点。
-
雷切尔你是对的。 CheckBox 在可视化树中不存在。它无处可去。我还能做什么?
-
@andrei.aliashkevich 很高兴看到你把它整理好 :)