我在c#WPF MVC中有一个应用程序。我的目标是创建一个标题栏,并为我的所有窗口调用它。C#WPF绑定自定义属性
我创造了这个:
XAML:
<Grid x:Class="Views.TitleBarView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:Views"
mc:Ignorable="d"
Style="{DynamicResource TitleStyleGrid}"
x:Name="barView">
<Label x:Name="labelAppName" Style="{DynamicResource TitleStyleLabel}" Content="{Binding Content, ElementName=barView}"/>
<Button x:Name="bttnClose" Style="{DynamicResource ButtonStyleCloseWindow}" Command="{Binding CloseCommand}"/>
</Grid>
C#:
public partial class TitleBarView : Grid
{
static TitleBarView()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(TitleBarView), new FrameworkPropertyMetadata(typeof(TitleBarView)));
}
public readonly static DependencyProperty ContentProperty = DependencyProperty.Register("Content", typeof(string), typeof(TitleBarView), new PropertyMetadata(""));
public string Content
{
get { return (string)GetValue(ContentProperty); }
set { SetValue(ContentProperty, value); }
}
public TitleBarView()
{
InitializeComponent();
TitleBarViewModel tvm = new TitleBarViewModel();
tvm.RequestClose += (s, e) => this.Close();
DataContext = tvm;
}
private void Close()
{
Window.GetWindow(this).Close();
}
}
我创建了财产Content
我Grid
和label
内绑定该属性。所以当我打电话给我的课TitleBarView
我只需要设置属性“内容”和标签自动更新。
它的工作原理很好,当我直接将内容与字符串:
<Window [...]
xmlns:local="clr-namespace:VectorReaderV3.Views"
[...]>
<local:TitleBarView x:Name="titleBar" Content="My Title"/>
<Window/>
但随着绑定,我有一个空标题:
<Window [...]
xmlns:local="clr-namespace:VectorReaderV3.Views"
[...]>
<local:TitleBarView x:Name="titleBar" Content="{Binding WindowTitle}">
<Window/>
我是怎么做了?
这个'Content =“{Binding WindowTitle}”'从哪里来? – lokusking
这是为什么你永远不应该显式设置自定义控件的DataContext的标准示例(就像你在TitleBarView构造函数中那样)。这样做有效地避免了继承一个DataContext,这是你在编写Content =“{Binding WindowTitle}”时隐含的期望。 – Clemens
我已经学会如此设置DataContext,最好的方法是什么? –