Microsoft.TeamFoundation.MVVMでValidation
2015年3月15日
最近作ってる「イベントログからPCの稼働時間を取得するアプリ」にエラーチェックを組み込んだ。
エラーはToolTipで表示している。
以下、手順。
Microsoft.TeamFoundation.MVVMのWindowViewModelは、ValidatingViewModelBaseから継承していてIDataErrorInfoを含んでいる。
1 2 |
public class WindowViewModel : ValidatingViewModelBase { |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
// 概要: // ビュー モデルの有効性認証をサポートする。 public class ValidatingViewModelBase : ViewModelBase, IDataErrorInfo { public ValidatingViewModelBase(ViewModelBase parentViewModel = null); // public ValidatingViewModelBase(Dispatcher dispatcher, ViewModelBase parentViewModel = null); // 概要: // 検証規則のコレクション。 // // 戻り値: // System.Collections.Generic.List<T> を返します。 public List<ValidationRule> ValidationRules { get; } // 概要: // 1 個以上の検証規則が壊れているかどうかを調べます。 // // 戻り値: // 検証規則が別の方法で失敗していない場合、は true。 public bool HasErrors(); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
// 概要: // ユーザー インターフェイスをバインドできる、カスタム エラー情報を提示するための機能を提供します。 public interface IDataErrorInfo { // 概要: // オブジェクトに関する間違いを示すエラー メッセージを取得します。 // // 戻り値: // オブジェクトに関する間違いを示すエラー メッセージ。 既定値は、空の文字列 ("") です。 string Error { get; } // 概要: // 指定した名前のプロパティに関するエラー メッセージを取得します。 // // パラメーター: // columnName: // エラー メッセージを取得する対象のプロパティの名前。 // // 戻り値: // プロパティに関するエラー メッセージ。 既定値は、空の文字列 ("") です。 string this[string columnName] { get; } |
ValidatingViewModelBaseのpublic List<ValidationRule> ValidationRules { get; }にValidationRuleを追加すれば、ViewのValidatesOnDataErrorsでエラー状態が表示できる。
ValidationRuleから継承した日付のValidationRuleを作って、
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
public class ValidationRuleDate : ValidationRule { public ValidationRuleDate(string name) : base(name) { } /// <summary> /// Validate /// </summary> /// <param name="viewModel"></param> /// <returns></returns> public override bool Validate(object viewModel) { var targetDate = this.GetPropertyValue(viewModel) as DateTime?; var today = DateTime.Now; var todayEndTime = new DateTime(today.Year, today.Month, today.Day, 23, 59, 59); // 未来日をチェック if (targetDate > todayEndTime) { Error = "未来日は指定できません"; return false; } var vm = viewModel as EventLogViewModel; // 日付の逆転をチェック var startDate = vm.StartDate; var endDate = vm.EndDate; if (startDate > endDate) { Error = "日付が逆転しています"; return false; } return true; } } |
ViewModelのコンストラクタで、ValidationRules に追加
1 2 3 4 |
// ValidationRulesを設定 ValidationRules.Add(new ValidationRuleDate("StartDate")); ValidationRules.Add(new ValidationRuleDate("EndDate")); } |
ViewのXAMLでValidatesOnDataErrors=Trueを設定
1 |
<DatePicker Name="startDate" SelectedDate="{Binding StartDate, ValidatesOnDataErrors=True}" Grid.Row="3" Grid.Column="1" Style="{StaticResource DatePickerStyle1}"> |
DatePickerのStyleでエラー時にToolTipを表示するようにする。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
: <!-- Validation.Errorの時の背景色設定 --> <VisualState x:Name="InvalidUnfocused"> <Storyboard> <ColorAnimation Storyboard.TargetName="PART_TextBox" Storyboard.TargetProperty="(Border.Background). (SolidColorBrush.Color)" To="Pink" Duration="0" /> <ColorAnimation Storyboard.TargetName="PART_TextBox" Storyboard.TargetProperty="(Foreground). (SolidColorBrush.Color)" To="Red" Duration="0" /> <BooleanAnimationUsingKeyFrames Storyboard.TargetName="PART_TextBox" Storyboard.TargetProperty="(ToolTipService.IsEnabled)" Duration="0"> <DiscreteBooleanKeyFrame Value="True" KeyTime="0" /> </BooleanAnimationUsingKeyFrames> </Storyboard> </VisualState> : <DatePickerTextBox x:Name="PART_TextBox" Grid.Column="0" Foreground="{TemplateBinding Foreground}" Focusable="{TemplateBinding Focusable}" HorizontalContentAlignment="Stretch" Grid.Row="0" VerticalContentAlignment="Stretch" ToolTipService.IsEnabled ="False"> <!-- ToolTipにエラーを表示する --> <DatePickerTextBox.ToolTip> <TextBlock Text="{Binding Path=(Validation.Errors)[0].ErrorContent, RelativeSource={RelativeSource TemplatedParent}}"/> </DatePickerTextBox.ToolTip> </DatePickerTextBox> |
「表示」ボタンが非活性になっているのは、CommandのCanExecuteでHasErrors()をみてTrue/Falseを返しているから。
1 2 3 4 5 6 7 8 9 10 11 |
// コマンド登録 ViewCommand = new RelayCommand( (x) => { GetData(StartDate, EndDate); } , (x) => { // ValidationRulesにより入力エラーがある場合は無効にする return !this.HasErrors(); }); |
DatePickerのStyleはMSDNのDatePicker のスタイルとテンプレートから。
ToolTipmpStyleはMSDNのToolTip のスタイルとテンプレートから。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 |
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <!--In this example, an implecit style for Calendar is defined elsewhere in the application. DatePickerCalendarStyle is based on the implicit style so that the DatePicker will use the application's calendar style.--> <!--<Style x:Key="DatePickerCalendarStyle" TargetType="{x:Type Calendar}" BasedOn="{StaticResource {x:Type Calendar}}" />--> <!--The template for the button that displays the calendar.--> <Style x:Key="DropDownButtonStyle" TargetType="Button"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type Button}"> <Grid> <VisualStateManager.VisualStateGroups> <VisualStateGroup x:Name="CommonStates"> <VisualStateGroup.Transitions> <VisualTransition GeneratedDuration="0" /> <VisualTransition GeneratedDuration="0:0:0.1" To="MouseOver" /> <VisualTransition GeneratedDuration="0:0:0.1" To="Pressed" /> </VisualStateGroup.Transitions> <VisualState x:Name="Normal" /> <VisualState x:Name="MouseOver"> <Storyboard> <ColorAnimationUsingKeyFrames BeginTime="0" Duration="00:00:00.001" Storyboard.TargetName="BackgroundGradient" Storyboard.TargetProperty="(Border.Background). (GradientBrush.GradientStops)[1].(GradientStop.Color)"> <SplineColorKeyFrame KeyTime="0" Value="#F2FFFFFF" /> </ColorAnimationUsingKeyFrames> <ColorAnimationUsingKeyFrames BeginTime="0" Duration="00:00:00.001" Storyboard.TargetName="BackgroundGradient" Storyboard.TargetProperty="(Border.Background). (GradientBrush.GradientStops)[2].(GradientStop.Color)"> <SplineColorKeyFrame KeyTime="0" Value="#CCFFFFFF" /> </ColorAnimationUsingKeyFrames> <ColorAnimation Duration="0" To="#FF448DCA" Storyboard.TargetProperty="(Border.Background). (SolidColorBrush.Color)" Storyboard.TargetName="Background" /> <ColorAnimationUsingKeyFrames BeginTime="0" Duration="00:00:00.001" Storyboard.TargetName="BackgroundGradient" Storyboard.TargetProperty="(Border.Background). (GradientBrush.GradientStops)[3].(GradientStop.Color)"> <SplineColorKeyFrame KeyTime="0" Value="#7FFFFFFF" /> </ColorAnimationUsingKeyFrames> </Storyboard> </VisualState> <VisualState x:Name="Pressed"> <Storyboard> <ColorAnimationUsingKeyFrames BeginTime="0" Duration="00:00:00.001" Storyboard.TargetName="Background" Storyboard.TargetProperty="(Border.Background). (SolidColorBrush.Color)"> <SplineColorKeyFrame KeyTime="0" Value="#FF448DCA" /> </ColorAnimationUsingKeyFrames> <DoubleAnimationUsingKeyFrames BeginTime="0" Duration="00:00:00.001" Storyboard.TargetProperty="(UIElement.Opacity)" Storyboard.TargetName="Highlight"> <SplineDoubleKeyFrame KeyTime="0" Value="1" /> </DoubleAnimationUsingKeyFrames> <ColorAnimationUsingKeyFrames BeginTime="0" Duration="00:00:00.001" Storyboard.TargetName="BackgroundGradient" Storyboard.TargetProperty="(Border.Background). (GradientBrush.GradientStops)[0].(GradientStop.Color)"> <SplineColorKeyFrame KeyTime="0" Value="#F4FFFFFF" /> </ColorAnimationUsingKeyFrames> <ColorAnimationUsingKeyFrames BeginTime="0" Duration="00:00:00.001" Storyboard.TargetName="BackgroundGradient" Storyboard.TargetProperty="(Border.Background). (GradientBrush.GradientStops)[1].(GradientStop.Color)"> <SplineColorKeyFrame KeyTime="0" Value="#EAFFFFFF" /> </ColorAnimationUsingKeyFrames> <ColorAnimationUsingKeyFrames BeginTime="0" Duration="00:00:00.001" Storyboard.TargetName="BackgroundGradient" Storyboard.TargetProperty="(Border.Background). (GradientBrush.GradientStops)[2].(GradientStop.Color)"> <SplineColorKeyFrame KeyTime="0" Value="#C6FFFFFF" /> </ColorAnimationUsingKeyFrames> <ColorAnimationUsingKeyFrames BeginTime="0" Duration="00:00:00.001" Storyboard.TargetName="BackgroundGradient" Storyboard.TargetProperty="(Border.Background). (GradientBrush.GradientStops)[3].(GradientStop.Color)"> <SplineColorKeyFrame KeyTime="0" Value="#6BFFFFFF" /> </ColorAnimationUsingKeyFrames> </Storyboard> </VisualState> <VisualState x:Name="Disabled" /> </VisualStateGroup> </VisualStateManager.VisualStateGroups> <Grid Background="#11FFFFFF" FlowDirection="LeftToRight" HorizontalAlignment="Center" Height="18" Margin="0" VerticalAlignment="Center" Width="19"> <Grid.ColumnDefinitions> <ColumnDefinition Width="20*" /> <ColumnDefinition Width="20*" /> <ColumnDefinition Width="20*" /> <ColumnDefinition Width="20*" /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="23*" /> <RowDefinition Height="19*" /> <RowDefinition Height="19*" /> <RowDefinition Height="19*" /> </Grid.RowDefinitions> <Border x:Name="Highlight" BorderThickness="1" Grid.ColumnSpan="4" CornerRadius="0,0,1,1" Margin="-1" Opacity="1" Grid.Row="0" Grid.RowSpan="4"> <Border.BorderBrush> <SolidColorBrush Color="{DynamicResource ControlPressedColor}" /> </Border.BorderBrush> </Border> <Border x:Name="Background" BorderBrush="#FFFFFFFF" BorderThickness="1" Grid.ColumnSpan="4" CornerRadius=".5" Margin="0,-1,0,0" Opacity="1" Grid.Row="1" Grid.RowSpan="3"> <Border.Background> <SolidColorBrush Color="{DynamicResource ControlDarkColor}" /> </Border.Background> </Border> <Border x:Name="BackgroundGradient" BorderBrush="#BF000000" BorderThickness="1" Grid.ColumnSpan="4" CornerRadius=".5" Margin="0,-1,0,0" Opacity="1" Grid.Row="1" Grid.RowSpan="3"> <Border.Background> <LinearGradientBrush EndPoint=".7,1" StartPoint=".7,0"> <GradientStop Color="#FFFFFFFF" Offset="0" /> <GradientStop Color="#F9FFFFFF" Offset="0.375" /> <GradientStop Color="#E5FFFFFF" Offset="0.625" /> <GradientStop Color="#C6FFFFFF" Offset="1" /> </LinearGradientBrush> </Border.Background> </Border> <Rectangle Grid.ColumnSpan="4" Grid.RowSpan="1" StrokeThickness="1"> <Rectangle.Fill> <LinearGradientBrush EndPoint="0,1" StartPoint="0,0"> <GradientStop Color="{DynamicResource HeaderTopColor}" /> <GradientStop Color="{DynamicResource ControlMediumColor}" Offset="1" /> </LinearGradientBrush> </Rectangle.Fill> <Rectangle.Stroke> <LinearGradientBrush EndPoint="0.48,-1" StartPoint="0.48,1.25"> <GradientStop Color="#FF494949" /> <GradientStop Color="#FF9F9F9F" Offset="1" /> </LinearGradientBrush> </Rectangle.Stroke> </Rectangle> <Path Fill="#FF2F2F2F" Grid.Row="1" Grid.Column="0" Grid.RowSpan="3" Grid.ColumnSpan="4" HorizontalAlignment="Center" VerticalAlignment="Center" RenderTransformOrigin="0.5,0.5" Margin="4,3,4,3" Stretch="Fill" Data="M11.426758,8.4305077 L11.749023,8.4305077 L11.749023,16.331387 L10.674805,16.331387 L10.674805,10.299648 L9.0742188,11.298672 L9.0742188,10.294277 C9.4788408,10.090176 9.9094238,9.8090878 10.365967,9.4510155 C10.82251,9.0929432 11.176106,8.7527733 11.426758,8.4305077 z M14.65086,8.4305077 L18.566387,8.4305077 L18.566387,9.3435936 L15.671368,9.3435936 L15.671368,11.255703 C15.936341,11.058764 16.27293,10.960293 16.681133,10.960293 C17.411602,10.960293 17.969301,11.178717 18.354229,11.615566 C18.739157,12.052416 18.931622,12.673672 18.931622,13.479336 C18.931622,15.452317 18.052553,16.438808 16.294415,16.438808 C15.560365,16.438808 14.951641,16.234707 14.468243,15.826504 L14.881817,14.929531 C15.368796,15.326992 15.837872,15.525723 16.289043,15.525723 C17.298809,15.525723 17.803692,14.895514 17.803692,13.635098 C17.803692,12.460618 17.305971,11.873379 16.310528,11.873379 C15.83071,11.873379 15.399232,12.079271 15.016094,12.491055 L14.65086,12.238613 z" /> <Ellipse Grid.ColumnSpan="4" Fill="#FFFFFFFF" HorizontalAlignment="Center" Height="3" StrokeThickness="0" VerticalAlignment="Center" Width="3" /> <Border x:Name="DisabledVisual" BorderBrush="#B2FFFFFF" BorderThickness="1" Grid.ColumnSpan="4" CornerRadius="0,0,.5,.5" Opacity="0" Grid.Row="0" Grid.RowSpan="4" /> </Grid> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style> <Style x:Key="DatePickerStyle1" TargetType="{x:Type DatePicker}"> <Setter Property="Foreground" Value="#FF333333" /> <Setter Property="IsTodayHighlighted" Value="True" /> <Setter Property="SelectedDateFormat" Value="Short" /> <Setter Property="Padding" Value="2" /> <Setter Property="BorderThickness" Value="1" /> <Setter Property="HorizontalContentAlignment" Value="Stretch" /> <!--Set CalendarStyle to DatePickerCalendarStyle.--> <!--<Setter Property="CalendarStyle" Value="{DynamicResource DatePickerCalendarStyle}" />--> <!-- カレンダースタイルを設定 --> <Setter Property="CalendarStyle" Value="{StaticResource ClenderStyle1}" /> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type DatePicker}"> <Border BorderThickness="{TemplateBinding BorderThickness}" Padding="{TemplateBinding Padding}"> <Border.BorderBrush> <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"> <GradientStop Color="{DynamicResource BorderLightColor}" Offset="0" /> <GradientStop Color="{DynamicResource BorderDarkColor}" Offset="1" /> </LinearGradientBrush> </Border.BorderBrush> <Border.Background> <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"> <GradientStop Color="{DynamicResource HeaderTopColor}" Offset="0" /> <GradientStop Color="{DynamicResource ControlMediumColor}" Offset="1" /> </LinearGradientBrush> </Border.Background> <VisualStateManager.VisualStateGroups> <VisualStateGroup x:Name="CommonStates"> <VisualState x:Name="Normal" /> <VisualState x:Name="Disabled"> <Storyboard> <DoubleAnimation Duration="0" To="1" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="PART_DisabledVisual" /> </Storyboard> </VisualState> <!-- Validation.Errorの時の背景色設定 --> <VisualState x:Name="InvalidUnfocused"> <Storyboard> <ColorAnimation Storyboard.TargetName="PART_TextBox" Storyboard.TargetProperty="(Border.Background). (SolidColorBrush.Color)" To="Pink" Duration="0" /> <ColorAnimation Storyboard.TargetName="PART_TextBox" Storyboard.TargetProperty="(Foreground). (SolidColorBrush.Color)" To="Red" Duration="0" /> <BooleanAnimationUsingKeyFrames Storyboard.TargetName="PART_TextBox" Storyboard.TargetProperty="(ToolTipService.IsEnabled)" Duration="0"> <DiscreteBooleanKeyFrame Value="True" KeyTime="0" /> </BooleanAnimationUsingKeyFrames> </Storyboard> </VisualState> </VisualStateGroup> </VisualStateManager.VisualStateGroups> <Grid x:Name="PART_Root" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"> <Grid.ColumnDefinitions> <ColumnDefinition Width="*" /> <ColumnDefinition Width="Auto" /> </Grid.ColumnDefinitions> <Button x:Name="PART_Button" Grid.Column="1" Foreground="{TemplateBinding Foreground}" Focusable="False" HorizontalAlignment="Left" Margin="3,0,3,0" Grid.Row="0" Style="{StaticResource DropDownButtonStyle}" VerticalAlignment="Top" /> <DatePickerTextBox x:Name="PART_TextBox" Grid.Column="0" Foreground="{TemplateBinding Foreground}" Focusable="{TemplateBinding Focusable}" HorizontalContentAlignment="Stretch" Grid.Row="0" VerticalContentAlignment="Stretch" ToolTipService.IsEnabled ="False"> <!-- ToolTipにエラーを表示する --> <DatePickerTextBox.ToolTip> <TextBlock Text="{Binding Path=(Validation.Errors)[0].ErrorContent, RelativeSource={RelativeSource TemplatedParent}}"/> </DatePickerTextBox.ToolTip> </DatePickerTextBox> <Grid x:Name="PART_DisabledVisual" Grid.ColumnSpan="2" Grid.Column="0" IsHitTestVisible="False" Opacity="0" Grid.Row="0"> <Grid.ColumnDefinitions> <ColumnDefinition Width="*" /> <ColumnDefinition Width="Auto" /> </Grid.ColumnDefinitions> <Rectangle Grid.Column="0" Fill="#A5FFFFFF" RadiusY="1" Grid.Row="0" RadiusX="1" /> <Rectangle Grid.Column="1" Fill="#A5FFFFFF" Height="18" Margin="3,0,3,0" RadiusY="1" Grid.Row="0" RadiusX="1" Width="19" /> <Popup x:Name="PART_Popup" AllowsTransparency="True" Placement="Bottom" PlacementTarget="{Binding ElementName=PART_TextBox}" StaysOpen="False" /> </Grid> </Grid> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style> </ResourceDictionary> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <Style x:Key="{x:Type ToolTip}" TargetType="ToolTip"> <Setter Property="OverridesDefaultStyle" Value="true" /> <Setter Property="HasDropShadow" Value="True" /> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="ToolTip"> <Border Name="Border" BorderThickness="1" Width="{TemplateBinding Width}" Height="{TemplateBinding Height}"> <Border.Background> <LinearGradientBrush StartPoint="0,0" EndPoint="0,1"> <LinearGradientBrush.GradientStops> <GradientStopCollection> <GradientStop Color="{DynamicResource ControlLightColor}" Offset="0.0" /> <GradientStop Color="{DynamicResource ControlMediumColor}" Offset="1.0" /> </GradientStopCollection> </LinearGradientBrush.GradientStops> </LinearGradientBrush> </Border.Background> <Border.BorderBrush> <SolidColorBrush Color="{DynamicResource BorderMediumColor}" /> </Border.BorderBrush> <ContentPresenter Margin="4" HorizontalAlignment="Left" VerticalAlignment="Top" /> </Border> <ControlTemplate.Triggers> <Trigger Property="HasDropShadow" Value="true"> <Setter TargetName="Border" Property="CornerRadius" Value="4" /> <Setter TargetName="Border" Property="SnapsToDevicePixels" Value="true" /> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> </ResourceDictionary> |