【发布时间】:2018-03-08 05:55:57
【问题描述】:
我正在尝试在我的窗口中传播一个字符串属性以显示标题。
在我的基类中,我使用默认的 get/set 设置了一个公共字符串属性。
在继承基类的窗口中,我尝试使用该属性作为窗口的标题。这失败了。但是,当我弹出一个消息框时,我肯定可以访问该属性。
如何在 WPF 窗口中显示来自基类的字符串属性?
代码:
BaseWindow.cs:
public class BaseWindow : Window
{
public string AppTitle { get; set; }
public string AppVersion { get; set; }
public BaseWindow()
{
AppTitle = "My Application";
AppVersion = "2.1";
}
...
}
MainWindow.xaml:
<src:BaseWindow x:Class=... >
<Window.Title>
<MultiBinding StringFormat="{}{0} - v{1}">
<Binding Path="AppTitle" />
<Binding Path="AppVersion" />
</MultiBinding>
</Window.Title>
这不会在MainWindow 中显示任何标题。
但是在 MainWindow 的 CodeBehind 中:
public MainWindow() : base()
{
InitializeComponent();
DataContext = new MainViewModel(new MyEntities());
System.Windows.Forms.MessageBox.Show(string.Format("App: {0}, v: {1}",
AppTitle, AppVersion));
}
我收到一个显示正确信息的消息框:
注意:多重绑定语法有效。在尝试从 BaseWindow 访问它之前,我尝试使用 Window 的 ViewModel 中的属性进行此操作。
基本原理是我想在应用程序中其他窗口的标题中显示子系统名称,例如“我的应用程序 - 小部件系统”,在子系统 VM 中只有子系统的名称。
【问题讨论】:
-
'Fails' 意味着根本没有标题。没有错误。没想到在 MessageBox 工作时寻找绑定错误。将仔细检查。
-
你必须在属性setter和getter中使用SetValue和GetValue。否则 .NET 属性不与 DependencyProperty 耦合
-
已更改,结果相同。在使用 BaseWindow 之前,我已尝试使用
typeof(Window)和typeof(MainWindow)。他们都没有工作。看起来我需要一个 BaseViewModel。 -
引号使用错误:使用
<Binding Path="AppTitle", RelativeSource="{RelativeSource Mode=Self}" /> -
@Clemens AppVer 在代码中得到更正。我会在问题中解决它。我很抱歉,但我想我已经把它变成了一个红鲱鱼。 AppTitle 应该仍然可以工作,如果这是问题所在,不是吗?
标签: c# wpf inheritance