我有一个view" title" property和我的datacontext设置为此VM。
我有TextBox
需要显示窗口的标题,当我在#34; .cs"中进行切换时需要更改它。文件背后。
我们怎样才能从" .cs"文件而不是来自viemodel?
<TextBlock VerticalAlignment="Top" HorizontalAlignment="Left"
Text="{Binding Title,RelativeSource={RelativeSource FindAncestor,AncestorType=Window}}"
Margin="10,8,0,0"/>
我正在从MSDN example
中抽取样本答案 0 :(得分: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(); }
}
}