如何绑定到ResourceDictionary中的控件元素

时间:2013-03-07 19:54:42

标签: wpf binding resourcedictionary

我正在尝试从该控件上的ResourceDictionary中引用我的WPF控件中的元素。这是一个例子:

<UserControl.Resources>
<ResourceDictionary>
    <Behaviors:GridViewInteractionModel x:Key="gridViewInteraction" GridView="{Binding ElementName=myGridView}"/>
</ResourceDictionary>
</UserControl.Resources>
...
<SomeGridView x:Name="myGridView"/>

GridView对象上的GridViewInteractionModel依赖项属性的值应该是名为SomeGridView的{​​{1}}对象。

以上代码不起作用。 myGridView不绑定元素({Binding ElementName=myGridView}的SetValue函数永远不会被调用)。

WPF运行时错误是:

GridViewInteractionModel

有没有人知道如何让控件中的元素绑定到ResourceDictionary中资源的属性?

我发现获取属性集的唯一方法是在调用Cannot find source for binding with reference 'ElementName=myGridView'. BindingExpression:(no path); DataItem=null; target element is 'GridViewInteractionModel' (HashCode=15238415); target property is 'GridView' (type 'SomeGridView') 后,在代码隐藏构造函数中手动设置它:

InitializeComponent()

但那真的很难看(容易出错)。

THX。

1 个答案:

答案 0 :(得分:0)

不完全确定你要在这里实现的目标。这是我处理listview及其子项的示例:

<Style x:Key="ListViewStyle" TargetType="ListView">
    <Setter Property="Background">
        <Setter.Value>
            <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                <GradientStop Color="#FFD3D1CF" Offset="0"/>
                <GradientStop Color="White" Offset="1"/>
            </LinearGradientBrush>
        </Setter.Value>
    </Setter>
    <Setter Property="Effect">
        <Setter.Value>
            <DropShadowEffect Opacity="0.7"/>
        </Setter.Value>
    </Setter>
</Style>
<Style x:Key="ListViewItemStyle" TargetType="ListViewItem">
    <Setter Property="Background" Value="#FF494646"/>
    <Setter Property="Foreground" Value="#FFFDFAFA"/>
    <Setter Property="Height" Value="25"></Setter>
    <Setter Property="Cursor" Value="Hand"></Setter>
    <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
            <Setter Property="Foreground" Value="Black"/>
        </Trigger>
        <Trigger Property="IsSelected" Value="True">
            <Setter Property="Foreground" Value="Black"/>
        </Trigger>
    </Style.Triggers>
</Style>


<ListView x:Name="lvwSettingsYears" x:Uid="lvwSettingsYears" Margin="10,77,10,50"
    Style="{DynamicResource ListViewStyle}"
    ItemContainerStyle="{DynamicResource ListViewItemStyle}"
    SelectionChanged="lvwYears_SelectionChanged">
    <ListView.View>
        <GridView>
            <GridViewColumn x:Name="SettingsYearListviewID" x:Uid="SettingsYearListviewID" DisplayMemberBinding="{Binding id}" Width="0"/>
            <GridViewColumn x:Name="SettingsYearListviewCode" x:Uid="SettingsYearListviewCode" Header="Code" DisplayMemberBinding="{Binding Code}" Width="100"/>
            <GridViewColumn x:Name="SettingsYearListviewDesc" x:Uid="SettingsYearListviewDesc" Header="Description" DisplayMemberBinding="{Binding Description}" Width="300"/>
        </GridView>
     </ListView.View>
 </ListView>

提示我发布此内容的原因在于它提到的错误消息 目标属性是 'GridView'(输入'SomeGridView')

我认为它正在寻找控制类型。