C# DynamicSource引发异常

C# DynamicSource引发异常,c#,wpf,binding,C#,Wpf,Binding,我必须将以下样式应用于我的列表视图项: <UserControl.Resources> <local:Look x:Key="ListViewItemLook" Background="Magenta"/> <Style x:Key="ListViewItemStyle" TargetType="{x:Type ListViewItem}"> <Style.Triggers> <Trigger Property="IsSele

我必须将以下样式应用于我的
列表视图项

<UserControl.Resources>

<local:Look x:Key="ListViewItemLook" Background="Magenta"/>


<Style x:Key="ListViewItemStyle" TargetType="{x:Type ListViewItem}">
<Style.Triggers>

    <Trigger Property="IsSelected" Value="True">
        <Setter Property="Background" Value="{Binding Source={DynamicResource ListViewItemLook}, Path=Background}"/>
    </Trigger>

</Style.Triggers>

</Style>

但我有一个例外,我试图改变:

<Setter Property="Background" Value="{Binding Path=Background}"/>

并添加到样式中:

<Setter Property="DataContext" Value="{DynamicResource ListViewItemLook}"/>

但这是行不通的。我无法绑定到StaticResource,因为我需要在运行时设置后台属性


我该怎么办?谢谢。

如果您希望local:Look和setter都使用相同的颜色,请执行一个小的重构:

将颜色拉出到单独的SolidColorBrush中,并使两个项目都引用它:

<SolidColorBrush x:Key="SelectedListViewItemBackground" Color="Magenta" />
<local:Look x:Key="whatever" Background="{StaticResource SelectedListViewItemBackground}" />
<Setter Property="Background" Value="{StaticResource SelectedListViewItemBackground}" />


如果您正在尝试执行其他操作,我无法理解这是什么,因为这个问题没有意义。

据我所知,DynamicSource扩展使用DependencyProperty机制(非常类似于绑定)。因此,无法使用DynamicSource设置绑定对象的Source属性,因为它不是DependencyProperty


另外,如果您想在资源中更改Look的Background属性,而不是Look本身;那么,将Look设置为绑定属性的静态资源应该不是问题。当然,Look类的Background属性应该触发PropertyChanged事件,或者是DependencyProperty本身。

Look类的Background属性是画笔还是颜色?如果背景是静态资源,当我在运行时更改它(SelectedListViewItemBackground)时,我的ListViewItem是否自动更新其背景?如果在运行时修改画笔的颜色,则不会。不过,通过使其成为DynamicSource,这很容易改变。除了将单词static改为dynamic之外,代码没有任何变化。