前提
VisualStudio 2022 で C# WPFプロジェクト
WPFでPrismフレームワークを利用しています。
実現したいこと
MainWindowにUserControlを複数インスタンスで張り付けたときに、
UserControlのそれぞれのインスタンスのプロパティをxamlで設定したい。
ViewModel側にBindingのプロパティを記載したい。
発生している問題・エラーメッセージ
記述の仕方がわかりません。
該当のソースコード
MainWindow.xaml
1<Window ・・・> 2 <Grid> 3 <local:PrismUserControl1 /> <==ここで、プロパティ"XXXXLabel"に値を入れて「いいいい」と表示したい。 4 <local:PrismUserControl1 XXXXLabel={Binging XXXX2Value} /> <==Bindingもしたい。 5 </Grid> 6</Window>
PrismUserControl1.xaml
1<UserControl ・・・> 2 <Grid> 3 <StackPanel Orientation="Horizontal"> 4 <Label Content="{Binding XXXXLabel}" /> 5 </StackPanel> 6 </Grid> 7</UserControl>
PrismUserControl1ViewModel.cs
1using Prism.Commands; 2using Prism.Mvvm; 3using System; 4using System.Collections.Generic; 5using System.Linq; 6 7namespace BlankApp.WPF.ViewModels 8{ 9 public class PrismUserControl1ViewModel : BindableBase 10 { 11 private string _xXXXLabel = "ああああ"; 12 public string XXXXLabel 13 { 14 get { return _xXXXLabel; } 15 set { SetProperty(ref _xXXXLabel, value); } 16 } 17 } 18} 19
試したこと
PrismUserControl1.xaml.cs にprismを利用しなければ、Bindingプロパティを記載できます。
ViewModel側にプロパティの受け渡しができないので、使いにくいです。
MainWindow.xaml.cs
1<Grid> 2 <StackPanel Orientation="Horizontal"> 3 <Views:PrismUserControl1 x:Name="Uc1" Width="100" XXXXValue="sssss"/> <==これは通ります 4 <Views:PrismUserControl1 x:Name="Uc2" Width="100" XXXXValue="{Binding XXXXValue}" /> <==これは通りません。(名前は便宜上共通) 5 </StackPanel> 6 </Grid>
MainWindowViewModel.cs
1 private string _xXXXValue = "いいいいいい"; 2 public string XXXXValue 3 { 4 get { return _xXXXValue; } 5 set { SetProperty(ref _xXXXValue, value); } 6 }
PrismUserControl1.xaml
1<UserControl ・・・> 2 <Grid> 3 <Label Content="{Binding XXXXValue,RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type local:PrismUserControl1}}}" Width="100" FontSize="50" /> 4 </Grid> 5</UserControl>
PrismUserControl1.xaml.cs
1using System.Windows; 2using System.Windows.Controls; 3 4namespace UC.WPF.Views 5{ 6 /// <summary> 7 /// Interaction logic for PrismUserControl1 8 /// </summary> 9 public partial class PrismUserControl1 : UserControl 10 { 11 public PrismUserControl1() 12 { 13 InitializeComponent(); 14 } 15 16 public string XXXXValue 17 { 18 get { return (string)GetValue(XXXXValueProperty); } 19 set { SetValue(XXXXValueProperty, value); } 20 } 21 // Using a DependencyProperty as the backing store for XXXXValue. This enables animation, styling, binding, etc... 22 public static readonly DependencyProperty XXXXValueProperty = 23 DependencyProperty.Register("XXXXValue", typeof(string), typeof(PrismUserControl1), new PropertyMetadata("ああああ")); 24 } 25} 26
補足情報(FW/ツールのバージョンなど)
VisualStudio 2022 C# .Net Core 6.0
prism の select container はUnity
