代码之家  ›  专栏  ›  技术社区  ›  erikH

如何绑定动态资源并指定路径

  •  9
  • erikH  · 技术社区  · 14 年前

    我想绑定到一个资源(dynamicResource)并访问该资源上的属性,但是否有一种方法可以做到这一点?

    (我希望在Visual Studio的XAML编辑器中可视化来自构造函数的默认值。通过DataContext或通过添加到我的窗口类上的属性引用对象时,无法看到这些内容…)

    不工作XAML: (在编写器中工作,但在运行时不工作…)

    <Window ... >
        <Window.Resources>
            <local:MyClass x:Key="myResource"  />
        </Window.Resources>
        <StackPanel>
            <Button Content="{Binding Source={DynamicResource myResource} Path=Property1}" />
            <Button Content="{Binding Source={DynamicResource myResource} Path=Property2}" />
        </StackPanel>
    </Window>
    

    使用类(可能需要实现InotifyPropertyChanged):

    public class MyClass 
    {
        public MyClass()
        {
            this.Property1 = "Ok";
            this.Property2 = "Cancel";
        }
        public string Property1 { get; set; }
        public string Property2 { get; set; }
    }
    
    2 回复  |  直到 6 年前
        1
  •  20
  •   Thomas Levesque    14 年前

    那是因为 DynamicResource 标记扩展只能用于依赖项属性,因为如果资源发生更改,则需要对其进行更新。和 Binding.Source 不是依赖属性…

    作为解决方案,您可以设置 DataContext 按钮的 动态资源 :

    <Button DataContext="{DynamicResource myResource}" Content="{Binding Path=Property1}" />
    <Button DataContext="{DynamicResource myResource}" Content="{Binding Path=Property2}" />
    
        2
  •  0
  •   Patrick Kursawe    6 年前

    滥用无关对象的数据上下文似乎是最简单的解决方法。 如果您仍然需要控件的DataContext(MVVM anyone?),您还可以在其他位置创建不可见的帮助器FrameworkElement:

    <FrameworkElement Visibility="Collapsed" x:Name="ControlBrushGetter"  DataContext=" 
    {DynamicResource {x:Static SystemColors.ControlBrushKey}}" />
    

    然后通过在绑定中使用名称来引用它:

    <SolidColorBrush Opacity="0.8" 
    Color="{Binding ElementName=ControlBrushGetter, Path=DataContext.Color}" />
    

    您的设计师很可能会抱怨在“对象”的上下文中无法解析“颜色”,但它在运行时工作得很好。