我的客户端应用程序可以连接到不同的服务器应用程序,因此我想将连接信息动态添加到窗口标题。标题绑定到 的属性,ViewModel
并get
在启动应用程序后调用它,但它不再更新,而窗口中的其他控件仍然正常工作。
这是XAML
:
<Window x:Class="MyApp.MainWindow"
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"
xmlns:localVM="clr-namespace:MyApp.ViewModels"
xmlns:local="clr-namespace:MyApp"
WindowStartupLocation="CenterScreen"
Title="{Binding Path=AppTitle}"
Height="459"
Width="810">
<Window.Resources>
[...]
<localVM:MainWindowViewModel x:Key="Windows1ViewModel" />
</Window.Resources>
<Grid DataContext="{StaticResource Windows1ViewModel}">
<Grid.RowDefinitions>
<RowDefinition Height="30" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Canvas Grid.Row="0">
<Menu DockPanel.Dock="Top" ItemsSource="{Binding Path=Menu}"/>
<Label Content="{Binding Path=ConnectionProperty}" Canvas.Right="0" Canvas.Bottom="0"/>
</Canvas>
</Grid>
</Window>
该Title
is bound to AppTitle
, while Label
is bound to ConnectionProperty
,这工作正常。在XAML.cs
我将 设置ViewModel
为DataContext
的View
:
public MainWindow()
{
InitializeComponent();
DataContext = new MainWindowViewModel();
}
的构造函数MainWindowViewModel
:
public MainWindowViewModel()
{
MenuItemViewModel server = new MenuItemViewModel { Text = ServerMenu };
Menu.Add(server);
AppTitle = "My application title";
SetConnectionMenuEntry(false);
//[.. dynamically build my menu ..]
}
启动应用程序后,Title
正确显示。然后我连接到服务器:
private void ConnectToServer()
{
//[.. connect to server ..]
if (connected)
{
SetConnectionMenuEntry(true);
ConnectionProperty = " - connected to " + serverProxy.url;
AppTitle = appTitle + connectionProperty;
}
}
在此之后,Title
保持不变,而Label
获得ConnectionProperty
价值。
这是两个属性的定义,几乎相同:
private string appTitle;
public string AppTitle
{
get { return appTitle; }
set
{
if (this.appTitle != value)
{
this.appTitle = value;
RaisePropertyChanged(() => AppTitle);
}
}
}
private string connectionProperty = "";
public string ConnectionProperty
{
get { return this.connectionProperty; }
set
{
if (this.connectionProperty != value)
{
this.connectionProperty = value;
RaisePropertyChanged(() => ConnectionProperty);
}
}
}
知道为什么Title
不更新,但是Label
?