我怎样才能实现以下的目标
<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,
new Binding(property) { Source = source });
}
}
用途如下:
<CheckBox Content="{Binding Caption}"
local:DynamicBinding.Property="{Binding PropertyName}"
local:DynamicBinding.Source="{Binding Source}"
local:DynamicBinding.Target="IsChecked" />
Target
可以是控件的任何依赖项属性。它是一个普通的字符串,不知道如何改进它,以获得intellisense的帮助时,进入它。
ToDo:如果更改了Target
(它将反映对Source
或Property
所做的更改),则不会删除绑定,不支持多个动态绑定(例如,对控件的不同属性)。
https://stackoverflow.com/questions/41482038
复制相似问题