【问题标题】:How to bind with dynamic resource and specifying a path如何绑定动态资源并指定路径
【发布时间】:2011-04-05 16:13:11
【问题描述】:

我想绑定到一个资源 (DynamicResource) 并访问该资源的属性,但有没有办法做到这一点?

(我想在 Visual Studio 的 xaml 编辑器中可视化来自构造函数的默认值。通过 DataContext 或通过我的 Window 类上添加的属性引用对象时看不到这些值...)

不工作 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; }
}

【问题讨论】:

    标签: visual-studio xaml binding dynamicresource


    【解决方案1】:

    滥用不相关对象的 DataContext 似乎是最简单的解决方法。 如果您仍然需要控件的 DataContext(任何人都可以使用 MVVM?),您还可以在其他地方创建一个不可见的帮助器 FrameworkElement:

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

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

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

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

    【讨论】:

      【解决方案2】:

      这是因为DynamicResource 标记扩展只能用于依赖属性,因为如果资源发生更改,它将需要更新它。而Binding.Source 不是依赖属性...

      作为一种解决方法,您可以将按钮的DataContext 设置为DynamicResource

      <Button DataContext="{DynamicResource myResource}" Content="{Binding Path=Property1}" />
      <Button DataContext="{DynamicResource myResource}" Content="{Binding Path=Property2}" />
      

      【讨论】:

      • +1,这似乎是一个更干净的工作,我已经这样做了,效果很好
      • 谁能解释为什么这只会在父窗口Loaded 事件触发后才起作用?即使使用 api etc TryFindResource() 后面的代码,它也会返回预期的资源?
      猜你喜欢
      • 2023-03-04
      • 1970-01-01
      • 2021-12-05
      • 2018-11-13
      • 1970-01-01
      • 1970-01-01
      • 2011-04-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多