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

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

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

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

XAML

XAML(Extensible Application Markup Language)はWPF、Silverlight、Windows PhoneそしてWindows Store appsでユーザーインターフェースを定義するために使われるXML言語です。

WPF

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

Q&A

1回答

6649閲覧

【WPF】【C#】一つのコントロールに複数のプロパティをバインドする。

KawaShige

総合スコア0

C#

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

XAML

XAML(Extensible Application Markup Language)はWPF、Silverlight、Windows PhoneそしてWindows Store appsでユーザーインターフェースを定義するために使われるXML言語です。

WPF

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

0グッド

0クリップ

投稿2020/12/15 06:07

前提・実現したいこと

一つのコントロールに複数のプロパティを紐づけたく、DetaTrrigerでDataContextを
切り替えるようにしたのですがうまくいかないです。そもそもこのようなことは可能なのでしょうか?可能であればDataContextのバインドでなくても良いので、いい方法を教えていただけますと幸いです。

発生している問題・エラーメッセージ

基になるDataContextが、初期状態でMeinじゃなくViewModelに変わっていることから、Passが見つからないのがエラーの原因だと考えています。

・ ・ ・ System.Windows.Data Error: 40 : BindingExpression path error: 'Pass' property not found on 'object' ''ViewModel' (HashCode=62883878)'. BindingExpression:Path=Pass; DataItem='ViewModel' (HashCode=62883878); target element is 'TextBlock' (Name=''); target property is 'NoTarget' (type 'Object') Process is terminated due to StackOverflowException. 型 'System.StackOverflowException' のハンドルされていない例外が mscorlib.dll で発生しました

該当のソースコード

C#

1namespace Test 2{ 3 class Mein : BindableBase 4 { 5 public DelegateCommand ButtonPush { get; set; } 6 7 public Mein() 8 { 9 ButtonPush = new DelegateCommand(Push); 10 } 11 12 public ViewModel VM1 { get; set; } = new ViewModel(); 13 public ViewModel VM2 { get; set; } = new ViewModel(); 14 15 bool _pass = false; 16 public bool Pass 17 { 18 get { return _pass; } 19 set { SetProperty(ref _pass, value); } 20 } 21 22 int i = 2; 23 private void Push() 24 { 25 i++; 26 if (i % 2 == 0) Pass = true; 27 else Pass = false; 28 29 VM1.Calculate(i); 30 VM2.Calculate(i); 31 } 32 } 33}

C#

1namespace Test 2{ 3 class ViewModel:BindableBase 4 { 5 int _a = 0; 6 public int A 7 { 8 get { return _a; } 9 set { SetProperty(ref _a, value); } 10 } 11 12 public void Calculate(int c) 13 { 14 int b = 2; 15 A = b * c; 16 } 17 } 18}

XAML

1<Window.DataContext> 2 <local:Mein/> 3 </Window.DataContext> 4 5 <Window.Resources> 6 <Style x:Key="Style" TargetType="{x:Type TextBlock}"> 7 <Style.Triggers> 8 <DataTrigger Binding="{Binding Pass}" Value="true"> 9 <Setter Property="DataContext" Value="{Binding VM1}"/> 10 </DataTrigger> 11 <DataTrigger Binding="{Binding Pass}" Value="false"> 12 <Setter Property="DataContext" Value="{Binding VM1}"/> 13 </DataTrigger> 14 </Style.Triggers> 15 </Style> 16 </Window.Resources> 17 18 <Grid> 19 <Grid.RowDefinitions> 20 <RowDefinition Height="1*"/> 21 <RowDefinition Height="1*"/> 22 </Grid.RowDefinitions> 23 <Button Command="{Binding ButtonPush}" Grid.Row="0" Content="Button" HorizontalAlignment="Center" VerticalAlignment="Center"/> 24 <TextBlock Grid.Row="1" Style="{StaticResource Style}" Text="{Binding A}" HorizontalAlignment="Center" VerticalAlignment="Center" /> 25 </Grid> 26

試したこと

基になるDetaContextがおかしくなっているのが原因だと考えたため、localで元のMeinのデータを参照するようにしたが、これでもうまくできません。

XAML

1<DataTrigger Binding="{Binding Path=(local:Mein.Pass)}" Value="true"> 2<Setter Property="DataContext" Value="{Binding VM1}"/> 3</DataTrigger>

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

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

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

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

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

guest

回答1

0

XY 問題な気がします。本当にやりたいことは何ですか?
「XY 問題」とは何ですか? - スタック・オーバーフローMeta

一つのコントロールに複数のプロパティを紐づけたく

複数のプロパティをバインドするなら、MultiBindingがあります。

BindingBase.StringFormat プロパティ (System.Windows.Data) | Microsoft Docs
IMultiValueConverter インターフェイス (System.Windows.Data) | Microsoft Docs

しかしコードを見るに「バインド先を切り替えたい」ように見えます。

であればViewModel側で、切り替え後の値を提供するのが真っ当に思います。
手を抜くなら2つコントロールを置いて、Visibilityを切り替えるとか^^;

Passが見つからないのがエラーの原因だと考えています。

Passが見つからないというかStackOverflowExceptionですので、MeinViewModelをぐるぐるしてしまうみたいな状況じゃないでしょうか(よくわかっていませんが^^;

BindingDataContextから探しますから、そのDataContext自身を切り替えたらダメでしょう(DataContextとは何なのかをしっかり意識しましょう)

どうしても今の形にこだわるなら、↓のようになっていないといけません。

xml

1<DataTrigger Binding="{Binding DataContext.Pass, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}" Value="true"> 2 <Setter Property="DataContext" Value="{Binding VM1}" /> 3</DataTrigger>

xml

1<Window 2 x:Class="Questions310362.MainWindow" 3 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 4 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 5 xmlns:local="clr-namespace:Questions310362" 6 Width="450" 7 SizeToContent="Height"> 8 <Window.DataContext> 9 <local:MainViewModel /> 10 </Window.DataContext> 11 <Window.Resources> 12 <BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" /> 13 <local:AConverter x:Key="AConverter" /> 14 15 <Style x:Key="Style" TargetType="{x:Type TextBlock}"> 16 <Style.Triggers> 17 <DataTrigger Binding="{Binding DataContext.Pass, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}" Value="true"> 18 <Setter Property="DataContext" Value="{Binding VM1}" /> 19 </DataTrigger> 20 <DataTrigger Binding="{Binding DataContext.Pass, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}" Value="false"> 21 <Setter Property="DataContext" Value="{Binding VM2}" /> 22 </DataTrigger> 23 </Style.Triggers> 24 </Style> 25 </Window.Resources> 26 <StackPanel> 27 <Button Command="{Binding ButtonPush}" Content="Button" /> 28 29 <GroupBox Margin="5" Header="StringFormat"> 30 <TextBlock> 31 <TextBlock.Text> 32 <MultiBinding StringFormat="VM1:{0}, VM2:{1}"> 33 <Binding Path="VM1.A" /> 34 <Binding Path="VM2.A" /> 35 </MultiBinding> 36 </TextBlock.Text> 37 </TextBlock> 38 </GroupBox> 39 40 <GroupBox Margin="5" Header="IMultiValueConverter"> 41 <TextBlock> 42 <TextBlock.Text> 43 <MultiBinding Converter="{StaticResource AConverter}"> 44 <Binding Path="Pass" /> 45 <Binding Path="VM1.A" /> 46 <Binding Path="VM2.A" /> 47 </MultiBinding> 48 </TextBlock.Text> 49 </TextBlock> 50 </GroupBox> 51 52 <GroupBox Margin="5" Header="切り替え後の値 VM"> 53 <TextBlock Text="{Binding VM.A}" /> 54 </GroupBox> 55 56 <GroupBox Margin="5" Header="切り替え後の値 A"> 57 <TextBlock Text="{Binding A}" /> 58 </GroupBox> 59 60 <GroupBox Margin="5" Header="手抜き"> 61 <Grid> 62 <TextBlock Text="{Binding VM2.A}" /> 63 <TextBlock 64 Background="White" 65 Text="{Binding VM1.A}" 66 Visibility="{Binding Pass, Converter={StaticResource BooleanToVisibilityConverter}}" /> 67 </Grid> 68 </GroupBox> 69 70 <GroupBox Margin="5" Header="DataTrigger"> 71 <TextBlock Style="{StaticResource Style}" Text="{Binding A}" /> 72 </GroupBox> 73 </StackPanel> 74</Window>

cs

1using Prism.Commands; 2using Prism.Mvvm; 3using System; 4using System.Diagnostics; 5using System.Globalization; 6using System.Windows; 7using System.Windows.Data; 8 9namespace Questions310362 10{ 11 internal class AConverter : IMultiValueConverter 12 { 13 public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) 14 { 15 if (values[0] is bool pass) return pass ? values[1].ToString() : values[2].ToString(); 16 return DependencyProperty.UnsetValue; 17 } 18 public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) => throw new NotSupportedException(); 19 } 20 21 internal class MainViewModel : BindableBase 22 { 23 private bool _pass; 24 public bool Pass { get => _pass; set => SetProperty(ref _pass, value); } 25 public ChildViewModel VM1 { get; } = new(); 26 public ChildViewModel VM2 { get; } = new(); 27 public ChildViewModel VM => Pass ? VM1 : VM2; 28 public int A => Pass ? VM1.A : VM2.A; 29 30 public DelegateCommand ButtonPush { get; } 31 32 public MainViewModel() => ButtonPush = new(Push); 33 34 private int i = 2; 35 private void Push() 36 { 37 Pass = ++i % 2 == 0; 38 VM1.Calculate(i); 39 VM2.Calculate(-i); // 違いが出ないのでマイナス 40 41 OnPropertyChanged(new(nameof(VM))); // VM変更通知 42 OnPropertyChanged(new(nameof(A))); // A変更通知 43 44 Debug.WriteLine($"VM1:{VM1.A}, VM2:{VM2.A}"); 45 } 46 } 47 48 internal class ChildViewModel : BindableBase 49 { 50 private int _a; 51 public int A { get => _a; set => SetProperty(ref _a, value); } 52 public void Calculate(int c) => A = 2 * c; 53 } 54 55 public partial class MainWindow : Window 56 { 57 public MainWindow() => InitializeComponent(); 58 } 59}

アプリ画像


BindableBaseDelegateCommandは、Prism.Coreを使用しました。
NuGet Gallery | Prism.Core 8.0.0.1909

特に指定がないので.NET 5.0で書きました^^
.NET Framework 4.8等では、new()でエラーが出るので型を書いてください。
Target-typed new expressions - C# 9.0 specification proposals | Microsoft Docs
ターゲットからの new 型推論 | ++C++; // 未確認飛行 C

投稿2020/12/15 08:36

編集2023/07/25 14:04
TN8001

総合スコア9244

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

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

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだベストアンサーが選ばれていません

会員登録して回答してみよう

アカウントをお持ちの方は

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

ただいまの回答率
85.50%

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

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

質問する

関連した質問