在 xaml 中设置自定义窗口属性
我有以下代码:
public partial class NewWindow: Window
{
public static readonly DependencyProperty PropNameProperty =
DependencyProperty.Register(
"PropName",
typeof(int),
typeof(NewWindow),
null);
public int PropName
{
get
{
return (int)GetValue(PropNameDependencyProperty);
}
set
{
SetValue(PropNameDependencyProperty, value);
}
}
现在,当我尝试使用我的新属性时,我无法编译:
<Window x:Class="AppName.NewWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:my="clr-namespace:AppName"
Title="NewWindow" Height="300" Width="300"
PropName="5" <-"property does not exist" error here
>
我可能只是误解了某些内容,但我不确定是什么。
I have the following code:
public partial class NewWindow: Window
{
public static readonly DependencyProperty PropNameProperty =
DependencyProperty.Register(
"PropName",
typeof(int),
typeof(NewWindow),
null);
public int PropName
{
get
{
return (int)GetValue(PropNameDependencyProperty);
}
set
{
SetValue(PropNameDependencyProperty, value);
}
}
Now when I try to use my new property I can't compile:
<Window x:Class="AppName.NewWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:my="clr-namespace:AppName"
Title="NewWindow" Height="300" Width="300"
PropName="5" <-"property does not exist" error here
>
I'm probably just misunderstanding something, but I'm not sure what.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
据我了解,它找不到该属性的原因是因为它是在 Window 类中查找它,而不是在 NewWindow 类中查找。为什么?因为XAML标记名称是Window,而不是NewWindow。
我尝试将标签更改为 NewWindow,但您实际上不能这样做,因为您的 XAML 和后面的代码正在协作定义 NewWindow 类,并且您无法根据其本身定义类。这就是为什么顶级 XAML 元素始终是父类的原因,这提出了一个解决方案:在继承自 Window 的新类中定义属性(为了便于论证,将其称为 ParentWindow),然后从中派生 NewWindow,所以你会得到类似
“我很欣赏这不一定是一个非常优雅的解决方案”的信息。
As I understand it, the reason it can't find the property is because it's looking for it in the Window class, not in your NewWindow class. Why? Because the XAML tag name is Window, not NewWindow.
I tried changing the tag to NewWindow, but you can't actually do that, because your XAML and the code behind are cooperating to define the NewWindow class and you can't define a class in terms of itself. This is why the toplevel XAML element is always the parent class, and this suggests a solution: define the property in a new class which inherits from Window (call it, for the sake of argument, ParentWindow), and then derive NewWindow from that, so you get something like
I appreciate this is not necessarily a very elegant solution.