gpt4 book ai didi

wpf - 带有绑定(bind)参数的 MarkupExtension

转载 作者:行者123 更新时间:2023-12-04 10:55:27 24 4
gpt4 key购买 nike

我正在定制 MarkupExtension其中我需要来自 XAML 的非字符串参数来构造新对象。是否可以在 DataContext 中的字段上使用非字符串参数绑定(bind)?范围?

换句话说,我怎么能做这样的事情?

<ListBox ItemsSource="{Binding Source={local:MyMarkupExtension {x:Type Button},IncludeMethods={Binding Source=CustomerObject.IsProblematic}}}" />

在哪里 IncludeMethods=CustomerObject.IsProblematic给我这个错误:

Binding cannot be set on the 'IncludeMethods' property of type 'TypeDescriptorExtension'. A 'Binding' can only be set on a DependencyProperty of a DependencyObject.



谁能帮我?

谢谢

最佳答案

我找到了解决这个问题的方法。
主要思想是为每个需要绑定(bind)的参数定义附加属性。

public class MarkupExtensionWithBindableParam : MarkupExtension
{
public BindingBase Param1 { get; set; } // its necessary to set parameter type as BindingBase to avoid exception that binding can't be used with non DependencyProperty

public override object ProvideValue(IServiceProvider serviceProvider)
{
IProvideValueTarget target = serviceProvider.GetService(typeof(IProvideValueTarget)) as IProvideValueTarget;
DependencyObject targetObject;
DependencyProperty targetProperty;

if (target != null && target.TargetObject is DependencyObject && target.TargetProperty is DependencyProperty)
{
targetObject = (DependencyObject)target.TargetObject;
targetProperty = (DependencyProperty)target.TargetProperty;
}
else
{
return this; // magic
}

// Bind the Param1 to attached property Param1BindingSinkProperty
BindingOperations.SetBinding(targetObject, MarkupExtensionWithBindableParam.Param1BindingSinkProperty, Param1);

// Now you can use Param1

// Param1 direct access example:
object param1Value = targetObject.GetValue(Param1BindingSinkProperty);

// Param1 use in binding example:
var param1InnerBinding = new Binding() { Source = targetObject, Path = new PropertyPath("(0).SomeInnerProperty", Param1BindingSinkProperty) }); // binding to Param1.SomeInnerProperty
return param1InnerBinding.ProvideValue(serviceProvider); // return binding to Param1.SomeInnerProperty
}

private static DependencyProperty Param1BindingSinkProperty = DependencyProperty.RegisterAttached("Param1BindingSink", typeof(object)// set the desired type of Param1 for at least runtime type safety check
, typeof(MarkupExtensionWithBindableParam ), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.Inherits));
}
用法很简单:
<TextBlock Text="{local:MarkupExtensionWithBindableParam Param1={Binding Path='SomePathToParam1'}}"/>

关于wpf - 带有绑定(bind)参数的 MarkupExtension,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10328802/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com