【问题标题】:Binding object property to UserControl DP error将对象属性绑定到 UserControl DP 错误
【发布时间】:2014-10-03 08:28:50
【问题描述】:

我在绑定此 UserControl aph:FilterItemControl 时遇到问题

Filter 对象具有属性:Negate、Valued 和 MatchCase。第一个和最后一个绑定都很好,但是Valued 不行。

<DataTemplate DataType="{x:Type helpers:Filter}">
    <Grid x:Name="FilterGrid" Margin="10,0,0,0" >
        <Grid.ColumnDefinitions>
            <ColumnDefinition />
            <ColumnDefinition />
            <ColumnDefinition />
        </Grid.ColumnDefinitions>

        <ToggleButton x:Name="NegationButton" 
                      IsChecked="{Binding Negate}"
                      Content="!"
                      Grid.Column="0" />

        <aph:FilterItemControl x:Name="FilterValueTbx" 
                               ToolTip="{Binding Valued}"
                               ValueType="{Binding CurrentPropertyFilter.PropertyType, Source={x:Static helpers:MyClass.Instance} }"
                               Grid.Column="1" />

        <ToggleButton x:Name="MatchCaseToggle" 
                      IsChecked="{Binding MatchCase}"
                      Content="Aa"
                      Grid.Column="2" >
        </ToggleButton>
    </Grid>
</DataTemplate>

错误:

System.Windows.Data 错误:40:
BindingExpression 路径错误: 在“对象”“FilterItemControl”上找不到“Valued”属性 (名称='UserControl')'。
绑定表达式:路径=值; DataItem='FilterItemControl' (Name='UserControl');
目标元素是 'FilterItemControl' (Name='UserControl');
目标属性是 “工具提示”(类型“对象”)

只是想知道为什么以及如何解决这个问题?

好像是跳转到UserControl的DataContext,为什么?

【问题讨论】:

    标签: wpf xaml


    【解决方案1】:

    您可以使用以下语法进入父元素的数据上下文:

      {Binding Path=PathToProperty, RelativeSource={RelativeSource AncestorType={x:Type typeOfAncestor}}}
    

    在您的示例中,您将使用以下内容:

    {Binding DataContext.Valued, 
                                  RelativeSource={RelativeSource FindAncestor,
                                                 AncestorType=Grid}}">
    

    【讨论】:

      【解决方案2】:

      看起来好像是在跳转到 UserControl 的 DataContext,为什么?

      如果您不提供绑定源,它将绑定到该元素的DataContext。我最好的猜测是您在控件内部更改了aph:FilterItemControlDataContext

      【讨论】:

      • 我认为它只会影响 UserControl 的内部而不是外部绑定,所以这很有趣!
      • 如果您只想影响UserControl 中的元素,请在UserControl 的内容上设置数据上下文。
      猜你喜欢
      • 1970-01-01
      • 2011-07-19
      • 2016-07-23
      • 1970-01-01
      • 2012-10-08
      • 2016-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多