相关疑难解决方法(0)

为什么我的数据绑定会看到真实值而不是强制值?

我正在编写一个真正的NumericUpDown/Spinner控件作为练习来学习自定义控件创作.我已经得到了我正在寻找的大部分行为,包括适当的强制.然而,我的一项测试显示出一个缺陷.

我的控制有3个依赖属性:Value,MaximumValue,和MinimumValue.我使用强制来确保Value在最小值和最大值之间保留,包括在内.例如:

// In NumericUpDown.cs

public static readonly DependencyProperty ValueProperty =
    DependencyProperty.Register("Value", typeof(int), typeof(NumericUpDown), 
    new FrameworkPropertyMetadata(0, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault | FrameworkPropertyMetadataOptions.Journal, HandleValueChanged, HandleCoerceValue));

[Localizability(LocalizationCategory.Text)]
public int Value
{
    get { return (int)this.GetValue(ValueProperty); }
    set { this.SetCurrentValue(ValueProperty, value); }
}

private static object HandleCoerceValue(DependencyObject d, object baseValue)
{
    NumericUpDown o = (NumericUpDown)d;
    var v = (int)baseValue;

    if (v < o.MinimumValue) v = o.MinimumValue;
    if (v > o.MaximumValue) v = o.MaximumValue;

    return v;
} …
Run Code Online (Sandbox Code Playgroud)

c# data-binding wpf xaml dependency-properties

13
推荐指数
2
解决办法
1849
查看次数

依赖属性强制绑定问题

我安装了VS2008和VS2010,我看到了一个非常奇怪的行为

在VS2008中,我有一个简单的WPF应用程序:

<TextBox x:Name="textbox" Text="{Binding Path=MyProperty,Mode=TwoWay}"></TextBox>
Run Code Online (Sandbox Code Playgroud)

public Window1()
{
    InitializeComponent();
    DataContext = this;
}
public string MyProperty
{
    get { return (string)GetValue(MyPropertyProperty); }
    set { SetValue(MyPropertyProperty, value); }
}
public static readonly DependencyProperty MyPropertyProperty = DependencyProperty.Register("MyProperty", typeof(string), typeof(Window1), new PropertyMetadata("default",null,Coerce));

private static object Coerce(DependencyObject d, object baseValue)
{
    return "Coerced Value";
}
Run Code Online (Sandbox Code Playgroud)

当我在文本框中输入随机字符串并点击标签时,我希望textbox.Text重置为"Coerced Value".如果我调试我看到应用程序在Coerce功能中断,但UI没有更新.

有趣的是,这个相同的代码在VS2010中工作,UI使用Coerced值进行更新.任何人都有想法发生了什么?

它是WPF错误吗?还是我错过了什么?

c# data-binding xaml coercion

8
推荐指数
1
解决办法
2799
查看次数

标签 统计

c# ×2

data-binding ×2

xaml ×2

coercion ×1

dependency-properties ×1

wpf ×1