[英]How to access a code behind property of ResourceDictionary in another XAML file?
現狀:有資源字典Class1.xaml用x背靠代碼隱藏類的Class1.cs:類。 類Class1.cs中有屬性MyHeight 。
目標:在XAML中訪問Property MyHeight 。
問題:它不會編譯並給出下一個錯誤:
引發異常:PresentationFramework.dll中的'System.Windows.Markup.XamlParseException'其他信息:'在'System.Windows.StaticResourceExtension'上提供值引發了異常。 行號“ 13”和行位置“ 41”。
解決方法:它可以在C#代碼中工作。
注意:它適用於單獨的Class或UserControl,但我需要ResourceDictionary。
問題:如何在MainWindow.xaml中訪問Class1.cs類的 MyHeight屬性 ?
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>
缺少的是ResourceDictionary
標記。
這也可以(代替上面的方法):
public Class1()
{
InitializeComponent();
Add("MyHeight", 20d);
}
InitializeComponent
重置Resources
字典,該字典解釋您的“這在代碼中起作用”-如果之后嘗試檢索“鍵”,則不會得到它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.