代码之家  ›  专栏  ›  技术社区  ›  Mark A. Donohoe

如果目标不是FrameworkElement,如何在代码隐藏中设置DynamicSource?

  •  -1
  • Mark A. Donohoe  · 技术社区  · 7 年前

    考虑这个BindingProxy类,它是Freezable的子类(因此当添加到 FrameworkElement Resources 收藏)。。。

    public class BindingProxy : Freezable {
    
        public BindingProxy(){}
        public BindingProxy(object value)
            => Value = value;
    
        protected override Freezable CreateInstanceCore()
            => new BindingProxy();
    
        #region Value Property
    
            public static readonly DependencyProperty ValueProperty = DependencyProperty.Register(
                nameof(Value),
                typeof(object),
                typeof(BindingProxy),
                new FrameworkPropertyMetadata(default));
    
            public object Value {
                get => GetValue(ValueProperty);
                set => SetValue(ValueProperty, value);
            }
    
        #endregion Value Property
    }
    

    你把它添加到你的XAML中,就像这样。。。

    <Window.Resources>
        <is:BindingProxy x:Key="TestValueProxy" Value="{DynamicResource TestValue}" />
    </Window.Resources>
    

    如你所见, Value 设置为 DynamicResource 因此,它将自动跟踪对该键定义的资源所做的更改。

    动态资源 ,你只要打个电话 SetResourceReference 就这样。。。

    myTextBlock.SetResourceReference(TextBlock.TextProperty, "MyTextResource")
    

    然而, 框架元件 对象,而不是 Freezable 所以你不能用这个 BindingProxy .

    挖掘源代码 FrameworkElement.SetResourceReference ,你发现这个。。。

    public void SetResourceReference(DependencyProperty dp, object name){
        base.SetValue(dp, new ResourceReferenceExpression(name));
        HasResourceReference = true;
    }
    

    不幸的是, ResourceReferenceExpression --这其中的“肉”是内在的,所以我也说不清楚。

    那么在代码隐藏中,如何设置 动态资源 可解冻的

    2 回复  |  直到 7 年前
        1
  •  1
  •   taquion    7 年前

    你可以使用 DynamicResourceExtension 代码中的实例:

    var proxy = new BindingProxy();
    var dynamicResourceExtension = new DynamicResourceExtension("TestValue");
    proxy.Value = dynamicResourceExtension.ProvideValue(null);
    

    here 你会看到的 ProvideValue 返回一个 ResourceReferenceExpression 什么时候 serviceProvider 为空。几乎和那件事一样 SetResourceReference

        2
  •  0
  •   mm8    7 年前

    创建 ResourceReferenceExpression 使用反射:

    Type type = typeof(System.Windows.Window).Assembly.GetType("System.Windows.ResourceReferenceExpression");
    ConstructorInfo ctor = type.GetConstructors()[0];
    object resourceReferenceExpression = ctor.Invoke(new object[] { "TestValue" });
    TestValueProxy.SetValue(BindingProxy.ValueProperty, resourceReferenceExpression);
    

    DynamicResource 价值 Freezable 动态地。

    推荐文章