質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.46%
C#

C#はマルチパラダイムプログラミング言語の1つで、命令形・宣言型・関数型・ジェネリック型・コンポーネント指向・オブジェクティブ指向のプログラミング開発すべてに対応しています。

MVVM

MVVM(Model View ViewModel)は構築上のデザインパターンで、表現ロジック(ViewModel)によってデータ(Model)からページ(View)を分離させます。

WPF

Windows Presentation Foundation (WPF) は、魅力的な外観のユーザー エクスペリエンスを持つ Windows クライアント アプリケーションを作成するための次世代プレゼンテーション システムです

Q&A

解決済

1回答

2871閲覧

ReactiveCommandにて複合条件での実行

TomeSq

総合スコア10

C#

C#はマルチパラダイムプログラミング言語の1つで、命令形・宣言型・関数型・ジェネリック型・コンポーネント指向・オブジェクティブ指向のプログラミング開発すべてに対応しています。

MVVM

MVVM(Model View ViewModel)は構築上のデザインパターンで、表現ロジック(ViewModel)によってデータ(Model)からページ(View)を分離させます。

WPF

Windows Presentation Foundation (WPF) は、魅力的な外観のユーザー エクスペリエンスを持つ Windows クライアント アプリケーションを作成するための次世代プレゼンテーション システムです

1グッド

0クリップ

投稿2020/09/02 08:07

c#でReactiveProperty(v5.4.0)を使ってGUI開発をしております。

以下の条件のときのみ、ボタンを活性化するCommandを作成したいです。

  1. ReactiveProperty Text1,Text2には何からしら入力されておりかつ、同じ値でない。
  2. ReactiveProperty Number1,Number2は0より大きくかつ、同じ値でない。

c#

1//条件 2public ReactiveProperty<string> Text1 { get; } 3public ReactiveProperty<int> Number1 { get; } 4public ReactiveProperty<string> Text2 { get; } 5public ReactiveProperty<int> Number2 { get; } 6 7//実行コマンド 8public ReactiveCommand Command { get; }

また、エラーの場合エラーメッセージも表示させることはできますでしょうか。
何卒宜しくお願いします。

TN8001👍を押しています

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

一応できましたが、地味に難しいですね^^;
普段ReactiveProperty使ってないので間違いや、もっといい方法があるかもしれません。
特にViewでのエラーをどうするか(HasViewError)は、考慮がいるかもしれませんね(ReactiveProperty<string> Number1としてしまってVM側でintにするとか)

NuGetMicrosoft.Xaml.Behaviors.Wpfを入れてください。

xml

1<Window 2 x:Class="Questions289115.MainWindow" 3 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 4 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 5 xmlns:i="http://schemas.microsoft.com/xaml/behaviors" 6 xmlns:local="clr-namespace:Questions289115" 7 Width="800" 8 Height="450"> 9 <Window.DataContext> 10 <local:ViewModel /> 11 </Window.DataContext> 12 13 <i:Interaction.Behaviors> 14 <local:ValidationErrorBehavior HasViewError="{Binding HasViewError.Value, Mode=OneWayToSource}" /> 15 </i:Interaction.Behaviors> 16 17 <Window.Resources> 18 <ControlTemplate x:Key="ValidationTemplate"> 19 <StackPanel> 20 <ItemsControl HorizontalAlignment="Right" ItemsSource="{Binding AdornedElement.(Validation.Errors), ElementName=validationTarget}"> 21 <ItemsControl.ItemsPanel> 22 <ItemsPanelTemplate> 23 <StackPanel Orientation="Horizontal" /> 24 </ItemsPanelTemplate> 25 </ItemsControl.ItemsPanel> 26 <ItemsControl.ItemTemplate> 27 <DataTemplate> 28 <TextBlock Foreground="Red" Text="{Binding ErrorContent}" /> 29 </DataTemplate> 30 </ItemsControl.ItemTemplate> 31 </ItemsControl> 32 <AdornedElementPlaceholder x:Name="validationTarget" /> 33 </StackPanel> 34 </ControlTemplate> 35 36 <Style TargetType="TextBox"> 37 <Setter Property="Validation.ErrorTemplate" Value="{StaticResource ValidationTemplate}" /> 38 </Style> 39 </Window.Resources> 40 41 <StackPanel> 42 <HeaderedContentControl Header="Text1"> 43 <TextBox Text="{Binding Text1.Value, UpdateSourceTrigger=PropertyChanged}" /> 44 </HeaderedContentControl> 45 <HeaderedContentControl Header="Number1"> 46 <TextBox Text="{Binding Number1.Value, UpdateSourceTrigger=PropertyChanged, NotifyOnValidationError=True}" /> 47 </HeaderedContentControl> 48 <HeaderedContentControl Header="Text2"> 49 <TextBox Text="{Binding Text2.Value, UpdateSourceTrigger=PropertyChanged}" /> 50 </HeaderedContentControl> 51 <HeaderedContentControl Header="Number2"> 52 <TextBox Text="{Binding Number2.Value, UpdateSourceTrigger=PropertyChanged, NotifyOnValidationError=True}" /> 53 </HeaderedContentControl> 54 55 <Button Command="{Binding Command}" Content="Command" /> 56 </StackPanel> 57</Window>

cs

1using System; 2using System.ComponentModel; 3using System.Diagnostics; 4using System.Linq; 5using System.Reactive.Linq; 6using System.Windows; 7using System.Windows.Controls; 8using Microsoft.Xaml.Behaviors; 9using Reactive.Bindings; 10using Reactive.Bindings.Extensions; 11 12namespace Questions289115 13{ 14 public class ViewModel : INotifyPropertyChanged 15 { 16 public ReactiveProperty<string> Text1 { get; } 17 public ReactiveProperty<string> Text2 { get; } 18 public ReactiveProperty<int> Number1 { get; } 19 public ReactiveProperty<int> Number2 { get; } 20 public ReactiveProperty<bool> HasViewError { get; } = new ReactiveProperty<bool>(); 21 22 public ReactiveCommand Command { get; } 23 24 public ViewModel() 25 { 26 Text1 = new ReactiveProperty<string>() 27 .SetValidateNotifyError(v => 28 { 29 // 正しく複数エラー対応するならこんなん?(もっとスッキリ書けない?^^; 30 var errors = new string[] { 31 string.IsNullOrEmpty(v) ? "何か入力してください。" : null, 32 v == Text2?.Value ? $"{nameof(Text2)}と同一です。" : null, 33 }.Where(x => x != null); 34 35 if(0 < errors.Count()) return errors; 36 return null; 37 }); 38 Text1.Subscribe(_ => Text2?.ForceValidate()); // もっといいのがありそう?? 39 40 Text2 = new ReactiveProperty<string>() 41 // 複数エラーとかどうでもいいなら 42 .SetValidateNotifyError(v => string.IsNullOrEmpty(v) ? "何か入力してください。" 43 : v == Text1?.Value ? $"{nameof(Text1)}と同一です。" : null); 44 Text2.Subscribe(_ => Text1?.ForceValidate()); 45 46 Number1 = new ReactiveProperty<int>() 47 .SetValidateNotifyError(v => 48 { 49 var errors = new string[] { 50 v < 0 ? "0以上を入力してください。" : null, 51 v == Number2?.Value ? $"{nameof(Number2)}と同一です。" : null, 52 }.Where(x => x != null); 53 54 if(0 < errors.Count()) return errors; 55 return null; 56 }); 57 Number1.Subscribe(_ => Number2?.ForceValidate()); 58 59 Number2 = new ReactiveProperty<int>() 60 .SetValidateNotifyError(v => 61 { 62 var errors = new string[] { 63 v < 0 ? "0以上を入力してください。" : null, 64 v == Number1?.Value ? $"{nameof(Number1)}と同一です。" : null, 65 }.Where(x => x != null); 66 67 if(0 < errors.Count()) return errors; 68 return null; 69 }); 70 Number2.Subscribe(_ => Number1?.ForceValidate()); 71 72 Command = new[] 73 { 74 Text1.ObserveHasErrors, 75 Text2.ObserveHasErrors, 76 Number1.ObserveHasErrors, 77 Number2.ObserveHasErrors, 78 HasViewError, 79 } 80 .CombineLatestValuesAreAllFalse() 81 .ToReactiveCommand(); 82 Command.Subscribe(() => Debug.WriteLine("Execute")); 83 } 84 85 public event PropertyChangedEventHandler PropertyChanged; 86 } 87 88 // [MVVMにおけるView層での入力値エラーの有無をViewModelで知る方法 - かずきのBlog@hatena](https://blog.okazuki.jp/entry/20110118/1295338167) 89 public class ValidationErrorBehavior : Behavior<DependencyObject> 90 { 91 public bool HasViewError 92 { 93 get => (bool)GetValue(HasViewErrorProperty); 94 set => SetValue(HasViewErrorProperty, value); 95 } 96 public static readonly DependencyProperty HasViewErrorProperty 97 = DependencyProperty.Register(nameof(HasViewError), typeof(bool), 98 typeof(ValidationErrorBehavior), new UIPropertyMetadata(false)); 99 private int errroCount; 100 protected override void OnAttached() 101 { 102 base.OnAttached(); 103 Validation.AddErrorHandler(AssociatedObject, ErrorHandler); 104 } 105 protected override void OnDetaching() 106 { 107 Validation.RemoveErrorHandler(AssociatedObject, ErrorHandler); 108 base.OnDetaching(); 109 } 110 private void ErrorHandler(object sender, ValidationErrorEventArgs e) 111 { 112 if(e.Action == ValidationErrorEventAction.Added) errroCount++; 113 else if(e.Action == ValidationErrorEventAction.Removed) errroCount--; 114 HasViewError = errroCount != 0; 115 } 116 } 117}

参考ページ
ReactiveProperty の Validation は DataAnnotation じゃないと思った? episode: 9 | :: halation ghost ::

WPFでTextBoxに入力エラーがないときだけ押せるボタンを実現したい - かずきのBlog@hatena

MVVMにおけるView層での入力値エラーの有無をViewModelで知る方法 - かずきのBlog@hatena

投稿2020/09/02 14:45

編集2023/07/23 05:10
TN8001

総合スコア9396

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

TomeSq

2020/09/03 00:34

ご回答ありがとうございます。 頂いたご回答をもとに無事に実装できそうです。 ありがとうございました。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.46%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問