WPFにもNumericUpDownみたいなのをユーザーコントロールで、その9、不具合修正
ダウンロード先
github.com
ここのControlLibraryCore20200620_v1.2.2.zip
作成動作環境
- Windows 10 Home バージョン 2004
- Visual Studio Community 2019
- WPF
- C#
- .NET Core 3.1
動作に必要なのは.NET Core 3.1がインストール済みのWindowsで、.NET Frameworkだけでは動かないはず
不具合修正
MyValueとBindingしている値が、MyMinValue(下限値)やMyMaxValue(上限値)を超えてしまうことがあるのを修正した
確認
MainWindow.xaml
<Window x:Class="_20210331_NumericUpDown9.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:_20210331_NumericUpDown9" xmlns:UpDown="clr-namespace:ControlLibraryCore20200620;assembly=ControlLibraryCore20200620" mc:Ignorable="d" Title="MainWindow" Height="250" Width="400"> <Grid> <StackPanel> <UpDown:NumericUpDown MyMaxValue="100" MyValue="{Binding Path=Value}" Name="MyUpDown" MySmallChange="1" MyLargeChange="10" FontSize="40" HorizontalAlignment="Center" MyStringFormat="MyValue = 000"/> <TextBlock Text="{Binding ElementName=MyUpDown, Path=MyValue}" FontSize="40" HorizontalAlignment="Center"/> <TextBlock Text="{Binding Path=Value}" FontSize="40" HorizontalAlignment="Center"/> <Button x:Name="MyButton" Content="test" Click="MyButton_Click"/> </StackPanel> </Grid> </Window>
上限値を100に指定、MyValueをValueとBinding
2つのTextBlockは確認用、上はNumericUpDownのMyValueを表示、下はValueを表示
MainWindow.xaml.cs
using System.Windows; namespace _20210331_NumericUpDown9 { public partial class MainWindow : Window { private Data MyData = new(); public MainWindow() { InitializeComponent(); this.DataContext = MyData; } private void MyButton_Click(object sender, RoutedEventArgs e) { var inu = MyUpDown.MyValue; var neko = MyData.Value; } } public class Data { public decimal Value { get; set; } = 100m; } }
Bindingする値Valueを持ったDataクラス
DataクラスをDataContextにしてBinding
旧バージョン
これを動かすと
初期値は100なので、ぜんぶ100
ここから▲を押して値を増やそうとすると
MyValue自体は上限値の100のままだけど、それとBindingしているValueのほうは上限値を超えて101になった
中の変数を見ても
101になってしまっている
今バージョン
この不具合を直したのが今回のバージョン1.2.2
期待通りの動作!
書き換えた場所
UserControl1.xaml.cs
MyValueプロパティのSetのところで上限下限をチェックするようにしただけ、これで直ったんだけど、MyValueはDependencyPropertyにしいるので、その
Registerの
これ(179行目~)
よくわからんけど値変更直前に実行されるCoerceってところ
ここ(227行目~)でチェックしてるから、Setのところでは必要ないと思っていたんだよねえ、実際はこれだけだと上限下限を超えてしまっていたので不十分だった
感想
要素同士のBindingだと正常で、DataContextでBindingした場合には不具合になるとかで今まで気づかなかったけど、直せてよかったわ
関連記事
新verは1年後
gogowaten.hatenablog.com
導入手順と履歴リンク
gogowaten.hatenablog.com
次回のWPF関連記事は1日後
gogowaten.hatenablog.com
前回のWPF記事は3日前
gogowaten.hatenablog.com
前回のNumericUpDown
gogowaten.hatenablog.com