2017-08-28 90 views
-2

我有一個viewmodel具有「title」屬性,我的datacontext設置爲此虛擬機。 我有一個TextBox需要顯示標題的窗口,它需要改變當我在後面的「.cs」文件channgin它。 我們如何從「.cs」文件的屬性綁定窗口標題而不是viemodel?窗口綁定到文本的標題

<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

試試這個:

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

代碼隱藏類應實現INotifyPropertyChanged接口,如果你打算能夠使用TextBox更改標題:

<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