2017-02-10 7 views
2

XAMLオブジェクト初期化子はCLRプロパティでどのように機能しますか?私はのXAML相当作成する必要がある場合XAMLのオブジェクト初期化子

public MainWindow() 
{ 
    InitializeComponent(); 

    this.DataContext = new MainWindowViewModel(); 
} 

を、それは次のようになります。私は

public string KeyFieldView { get; set; } 

public MainWindow() 
{ 
    InitializeComponent(); 

    this.DataContext = new MainWindowViewModel() 
    { 
     KeyFieldVM=KeyFieldView 
    }; 
} 

<Window.DataContext> 
    <vm:MainWindowViewModel/> 
</Window.DataContext> 

をしかし、私はこのような何かをしたい場合KeyFieldVM=""まで取得できますが、KeyFieldViewにどうやってアクセスすればよいか分かりません。

<Window.DataContext> 
    <vm:MainWindowViewModel KeyFieldVM=""/> 
</Window.DataContext> 
+2

これは、MSがそんなに私を怒らせる理由です。あなたが求めていることはXAML-2009では簡単ですが、WPFは元のバージョンのXAMLしかサポートしていません。 –

答えて

2

あなたはKeyFieldVMプロパティを結合することができるが、それは依存関係プロパティであることを提供する:

public class MainWindowViewModel : DependencyObject 
{ 
    public static readonly DependencyProperty KeyFieldVMProperty = 
     DependencyProperty.Register("KeyFieldVM", typeof(string), 
      typeof(MainWindowViewModel), new FrameworkPropertyMetadata("ok")); 

    public string KeyFieldVM 
    { 
     get { return (string)GetValue(KeyFieldVMProperty); } 
     set { SetValue(KeyFieldVMProperty, value); } 
    } 
} 

<Window ... x:Name="win"> 
    <Window.DataContext> 
     <vm:MainWindowViewModel KeyFieldVM="{Binding KeyFieldView, ElementName=win}"/> 
    </Window.DataContext> 
    <Grid> 
     <TextBlock Text="{Binding KeyFieldVM}" /> 
    </Grid> 
</Window> 

これはしかしDependencyObjectするビューモデルを必要とし、これには欠点があります:

INotifyPropertyChanged vs. DependencyProperty in ViewModel

XAMLがマークアップ言語。あなたは、プログラムのビューモデルを作成する必要があり、これを行うにしたい場合は、ビューのコードビハインドでは、たとえば、

<vm:MainWindowViewModel KeyFieldVM="{this.KeyFieldView}"/> <!-- BAD MARKUP --> 

:あなたはこのような何かを行うことができないので、それは変数の任意の概念がありません。

+0

しかし、通常のCLRプロパティにアクセスするための依存プロパティを作成する必要はなく、バインディングを回避できますが、唯一の方法です。 – Simsons

+1

任意の* target *プロパティ、つまり* *を*にバインドするプロパティビューは依存関係プロパティでなければなりません。 – mm8

2

あなたは、オブジェクトのインスタンス化にコンストラクタ引数に渡すことthis answerに示されているようにObjectDataProviderを使用することができます。ただし、these parameters can't be bound。したがって、動的プロパティ値はコンストラクタで使用できません。

これらのプロパティを定数にして、それらをXAMLから渡すか、コードの背後から埋めてください。