Situation: There is ResourceDictionary Class1.xaml backed by code behind Class Class1.cs using x:Class. There is Property MyHeight inside Class Class1.cs .
Goal: To access Property MyHeight in XAML.
Problem: It doesn't compile giving the next error:
Exception thrown: 'System.Windows.Markup.XamlParseException' in PresentationFramework.dll Additional information: 'Provide value on 'System.Windows.StaticResourceExtension' threw an exception.' Line number '13' and line position '41'.
Workaround: It works in C# code.
Note: It works for separate Class or UserControl, but I need it for ResourceDictionary.
Question: How to access Property MyHeight of Class Class1.cs in MainWindow.xaml ?
Class1.xaml:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication2"
x:Class="WpfApplication2.Class1">
Class1.cs:
partial class Class1
{
public Class1()
{
InitializeComponent();
}
public double MyHeight
{
get { return 20; }
set { }
}
}
MainWindow.xaml:
<Window.Resources>
<local:Class1 x:Key="MyClass"></local:Class1>
</Window.Resources>
<Grid>
<Ellipse Fill="Red" Width="100" Height="{Binding Source={StaticResource MyClass}, Path=MyHeight}"></Ellipse>
</Grid>
MainWindow.xaml.cs:
public partial class MainWindow : Window
{
public MainWindow()
{
this.Resources.Add("key", new Class1());
MessageBox.Show(((Class1)this.Resources["key"]).MyHeight.ToString()); // Works
InitializeComponent();
}
}
<Window.Resources>
<ResourceDictionary>
<local:Class1 x:Key="MyClass" />
</ResourceDictionary>
</Window.Resources>
What's missing is the ResourceDictionary
tag.
This also works (as a replacement for the above):
public Class1()
{
InitializeComponent();
Add("MyHeight", 20d);
}
InitializeComponent
resets the Resources
dictionary, which explains your "this works in code" -- if you try to retrieve "key" after, you won't get it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.