我怎样才能实现以下的目标
<CheckBox Content="{Binding Caption}">
<CheckBox.IsChecked>
<Binding Path="{Binding PropertyName}"
Source="{Binding Source}" />
</CheckBox.IsChecked>
</CheckBox>
哪里
public class ViewModel
public string Caption { get; } = "Test";
public string PropertyName { get; } = nameof(Test.Property);
public object Source { get; } = new Test();
public class Test
public bool Property { get; set; } = false;
}
其思想是通过属性为绑定提供
Path
和
Source
(设计时未知)。
当前,此抛出异常位于
<Binding Path=
行。
不能在“绑定”类型的“路径”属性上设置“绑定”。“绑定”只能设置在DependencyProperty的DependencyObject上。
发布于 2017-01-05 14:45:48
在看到@WPFUser one之后,回答有点晚,但它支持任何属性,我个人不喜欢混合依赖关系:
public class DynamicBinding
public static object GetSource(DependencyObject obj) => (object)obj.GetValue(SourceProperty);
public static void SetSource(DependencyObject obj, object value) => obj.SetValue(SourceProperty, value);
public static readonly DependencyProperty SourceProperty =
DependencyProperty.RegisterAttached("Source", typeof(object), typeof(DynamicBinding), new PropertyMetadata(null, (d, e) => SetBinding(d)));
public static string GetProperty(DependencyObject obj) => (string)obj.GetValue(PropertyProperty);
public static void SetProperty(DependencyObject obj, string value) => obj.SetValue(PropertyProperty, value);
public static readonly DependencyProperty PropertyProperty =
DependencyProperty.RegisterAttached("Property", typeof(string), typeof(DynamicBinding), new PropertyMetadata(null, (d, e) => SetBinding(d)));
public static string GetTarget(DependencyObject obj) => (string)obj.GetValue(TargetProperty);
public static void SetTarget(DependencyObject obj, string value) => obj.SetValue(TargetProperty, value);
public static readonly DependencyProperty TargetProperty =
DependencyProperty.RegisterAttached("Target", typeof(string), typeof(DynamicBinding), new PropertyMetadata(null, (d, e) => SetBinding(d)));
static void SetBinding(DependencyObject obj)
var source = GetSource(obj);
var property = GetProperty(obj);
var target = GetTarget(obj);
// only if all required attached properties values are set
if (source == null || property == null || target == null)
return;
BindingOperations.SetBinding(obj, DependencyPropertyDescriptor.FromName(target, obj.GetType(), obj.GetType()).DependencyProperty,
![]() |
欢快的南瓜 · HTTP请求示例--AI中台公用文档-火山引擎 2 月前 |