Reputation: 19897
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.
Upvotes: 2
Views: 2036
Reputation: 9959
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
<local:ParentWindow x:Class="TestApp.NewWindow"
PropName="5"
xmlns:local="clr-namespace:TestApp"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
...
</local:ParentWindow>
I appreciate this is not necessarily a very elegant solution.
Upvotes: 4