[英]Bind Control/Window property to custom property and set default value
I'm trying to bind the Title
property of a Window
to a custom property of this Window
. 我试图将
Window
的Title
属性绑定到此Window
的自定义属性。 The XAML looks like this: XAML看起来像这样:
Title="{Binding Path=WindowTitle, RelativeSource={RelativeSource Mode=Self}}"
The code behind like this: 后面的代码是这样的:
public string WindowTitle
{
get
{
string title = (string)GetValue(WindowTitleProperty);
title = string.IsNullOrEmpty(title) ? "Editor" : title;
return title;
}
set
{
SetValue(WindowTitleProperty, value);
}
}
public static readonly DependencyProperty WindowTitleProperty =
DependencyProperty.Register("WindowTitle", typeof(string), typeof(Editor), new UIPropertyMetadata(null));
This works good after the property WindowTitle
was set to a new value. 将属性
WindowTitle
设置为新值后,此方法效果很好。 But unfortunately upon loading the Window
I don't get any title. 但是不幸的是,在加载
Window
我没有任何标题。 The getter of WindowTitle
isn't even called. 甚至没有调用
WindowTitle
的吸气剂。 As far as I can say, it never gets called. 据我所知,它永远不会被调用。 What am I doing wrong?
我究竟做错了什么? Why is the getter never called (even when the title is set correctly)?
为什么从未调用getter(即使正确设置了标题)? Can I set a defaultvalue on any other way?
我可以通过其他方式设置默认值吗?
Your property looks strange. 您的财产看起来很奇怪。 Why is it defined as a dependency property to begin with?
为什么首先将其定义为依赖项属性? You might as well use a CLR property and implement the
INotifyPropertyChanged
interface. 您也可以使用CLR属性并实现
INotifyPropertyChanged
接口。 This works fine for me: 这对我来说很好:
public partial class Window13 : Window, INotifyPropertyChanged
{
public Window13()
{
InitializeComponent();
}
private string _windowTitle = "default title...";
public string WindowTitle
{
get { return _windowTitle; }
set { _windowTitle = value; NotifyPropertyChanged(); }
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
The CLR getter of a dependency property should only call the GetValue
method and not contain any other logic. 依赖项属性的CLR获取器应仅调用
GetValue
方法,并且不包含任何其他逻辑。
Edit: If you do want a dependency property for some reason, it should be implemented like this: 编辑:如果您确实出于某种原因想要依赖项属性,则应按以下方式实现:
public string WindowTitle
{
get
{
return (string)GetValue(WindowTitleProperty);
}
set
{
SetValue(WindowTitleProperty, value);
}
}
public static readonly DependencyProperty WindowTitleProperty =
DependencyProperty.Register("WindowTitle", typeof(string), typeof(Editor), new UIPropertyMetadata("Editor"));
Note that you specify the default value when you register the property. 请注意,在注册属性时,请指定默认值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.