gpt4 book ai didi

wpf - 来自 XAML 中只读属性的 OneWayToSource 绑定(bind)

转载 作者:行者123 更新时间:2023-12-03 05:17:22 26 4
gpt4 key购买 nike

我正在尝试以 OneWayToSource 作为模式绑定(bind)到 Readonly 属性,但似乎无法在 XAML 中完成:

<controls:FlagThingy IsModified="{Binding FlagIsModified, 
ElementName=container,
Mode=OneWayToSource}" />

我得到:

The property 'FlagThingy.IsModified' cannot be set because it does not have an accessible set accessor.

IsModifiedFlagThingy 上的只读 DependencyProperty。我想将该值绑定(bind)到容器上的 FlagIsModified 属性。

需要明确的是:

FlagThingy.IsModified --> container.FlagIsModified
------ READONLY ----- ----- READWRITE --------

仅使用 XAML 可以吗?

<小时/>

更新:嗯,我通过在容器上而不是在 FlagThingy 上设置绑定(bind)来解决此问题。但我还是想知道这是否可能。

最佳答案

OneWayToSource 的一些研究结果...

选项#1。

// Control definition
public partial class FlagThingy : UserControl
{
public static readonly DependencyProperty IsModifiedProperty =
DependencyProperty.Register("IsModified", typeof(bool), typeof(FlagThingy), new PropertyMetadata());
}
<controls:FlagThingy x:Name="_flagThingy" />
// Binding Code
Binding binding = new Binding();
binding.Path = new PropertyPath("FlagIsModified");
binding.ElementName = "container";
binding.Mode = BindingMode.OneWayToSource;
_flagThingy.SetBinding(FlagThingy.IsModifiedProperty, binding);

选项#2

// Control definition
public partial class FlagThingy : UserControl
{
public static readonly DependencyProperty IsModifiedProperty =
DependencyProperty.Register("IsModified", typeof(bool), typeof(FlagThingy), new PropertyMetadata());

public bool IsModified
{
get { return (bool)GetValue(IsModifiedProperty); }
set { throw new Exception("An attempt ot modify Read-Only property"); }
}
}
<controls:FlagThingy IsModified="{Binding Path=FlagIsModified, 
ElementName=container, Mode=OneWayToSource}" />

选项#3(真正的只读依赖属性)

System.ArgumentException:“IsModified”属性无法进行数据绑定(bind)。

// Control definition
public partial class FlagThingy : UserControl
{
private static readonly DependencyPropertyKey IsModifiedKey =
DependencyProperty.RegisterReadOnly("IsModified", typeof(bool), typeof(FlagThingy), new PropertyMetadata());

public static readonly DependencyProperty IsModifiedProperty =
IsModifiedKey.DependencyProperty;
}
<controls:FlagThingy x:Name="_flagThingy" />
// Binding Code
Same binding code...

Reflector 给出了答案:

internal static BindingExpression CreateBindingExpression(DependencyObject d, DependencyProperty dp, Binding binding, BindingExpressionBase parent)
{
FrameworkPropertyMetadata fwMetaData = dp.GetMetadata(d.DependencyObjectType) as FrameworkPropertyMetadata;
if (((fwMetaData != null) && !fwMetaData.IsDataBindingAllowed) || dp.ReadOnly)
{
throw new ArgumentException(System.Windows.SR.Get(System.Windows.SRID.PropertyNotBindable, new object[] { dp.Name }), "dp");
}
....

关于wpf - 来自 XAML 中只读属性的 OneWayToSource 绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/658170/

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