我正在寫一個真實的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;
}
我的測試只是爲了確保數據綁定工作如何我期望。我創建了一個默認的WPF Windows應用程序,並在下面的XAML拋出:
<Window x:Class="WpfApplication.MainWindow" x:Name="This"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:nud="clr-namespace:WpfCustomControlLibrary;assembly=WpfCustomControlLibrary"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<nud:NumericUpDown Value="{Binding ElementName=This, Path=NumberValue}"/>
<TextBox Grid.Row="1" Text="{Binding ElementName=This, Path=NumberValue, Mode=OneWay}" />
</Grid>
</Window>
用非常簡單的代碼隱藏:
public partial class MainWindow : Window
{
public int NumberValue
{
get { return (int)GetValue(NumberValueProperty); }
set { SetCurrentValue(NumberValueProperty, value); }
}
// Using a DependencyProperty as the backing store for NumberValue. This enables animation, styling, binding, etc...
public static readonly DependencyProperty NumberValueProperty =
DependencyProperty.Register("NumberValue", typeof(int), typeof(MainWindow), new UIPropertyMetadata(0));
public MainWindow()
{
InitializeComponent();
}
}
(我省略了控制的介紹了XAML)
現在如果我運行此操作,我會在文本框中看到NumericUpDown
中的值恰當地反映出來,但如果輸入的值超出範圍,則超出範圍的值將顯示在測試文本框中,而NumericUpDown
將顯示正確的值。
這是如何強制值應該採取行動?它在UI中被強制是好的,但我也希望被強制的值也能通過數據綁定。
似乎綁定不支持認識val。你在TextBox中試過差異模式嗎? – 2010-07-24 02:08:08