2017-08-28 94 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