2017-08-28 4 views
-2

"title"プロパティを持つviewmodelが1つあり、datacontextがこのVMに設定されています。 私はウィンドウのタイトルを表示する必要があるTextBoxを持っています。私はそれを後ろの ".cs"ファイルに入れ替える必要があります。 viemodelではなく、 ".cs"ファイルのプロパティからウィンドウのタイトルをバインドするにはどうすればいいですか?テキストへのウィンドウのタイトルのバインド

<TextBlock VerticalAlignment="Top" HorizontalAlignment="Left" 
      Text="{Binding Title,RelativeSource={RelativeSource FindAncestor,AncestorType=Window}}" 
      Margin="10,8,0,0"/> 

私はこのお試しくださいMSDN example

+0

'TextBox.Text'は' VM.Title'にバインドされていますか?もしそうなら、なぜあなたは 'Textbox.Text'をコードビハインドから変更したいのですか? – Dennis

+0

いくつかのコードが役に立ちます。 –

+0

murmansk

答えて

2

からサンプルを取っています:あなたはTextBoxを使用してタイトルを変更できるようにする予定の場合は、コードビハインドクラスがINotifyPropertyChangedインタフェースを実装する必要があり

<Window ... Title="{Binding TitleProperty, RelativeSource={RelativeSource Self}}" 

を:

<Window x:Class="WpfApplication1.Window1" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
     mc:Ignorable="d" 
     Title="{Binding MyTitle, RelativeSource={RelativeSource Self}}" Height="300" Width="300"> 
    <StackPanel> 
     <TextBox Text="{Binding MyTitle, UpdateSourceTrigger=PropertyChanged, RelativeSource={RelativeSource AncestorType=Window}}" /> 
    </StackPanel> 
</Window> 

public partial class Window1 : Window, INotifyPropertyChanged 
{ 
    public Window1() 
    { 
     InitializeComponent(); 
    } 

    public event PropertyChangedEventHandler PropertyChanged; 
    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "") 
    { 
     if (PropertyChanged != null) 
      PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 
    } 

    private string _title; 
    public string MyTitle 
    { 
     get { return _title; } 
     set { _title = value; NotifyPropertyChanged(); } 
    } 
} 
+0

はMSDNと似ています私が試している例では完全な画像を提供していません https://msdn.microsoft.com/en-us/library/system.windows.shell.windowchrome(v=vs.110).aspx – murmansk

+0

ursは良いですMSDNを批判する – murmansk