試試這個:
<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(); }
}
}
來源
2017-08-28 12:28:09
mm8
將'Textbox.Text'綁定到'VM.Title'?如果是這樣,你爲什麼要將'Textbox.Text'從代碼隱藏中更改? – Dennis
一些代碼將是有用的。 –