![](/img/trans.png)
[英]How to bind a XDocument object to a Treeview without using codebehind?
[英]How to get the actual object of StaticResource from codebehind without using TryFindResource?
我在XAML文件中使用了StaticResource
。 我已經使用x:Name
命名了StaticResource
。 現在,我想訪問StaticResource
的實際對象。
這些是文件:
在XAML文件中:
<Window x:Class="MyProject.MainWindow"
...
Title="MainWindow" Height="350" Width="525">
<Grid>
<StaticResource ResourceKey="MyButtonResource" x:Name="MyResource" />
</Grid>
</Window>
在隱藏代碼的CS文件中:
Button buttonFromStaticResource = MyResource.SomeProperty as Button;
在這里,我需要類似SomeProperty
方法或任何方法來獲取實際的對象(在這種情況下,它是一個Button
對象)。
編輯:
獲取對象的一種方法是使用TryFindResource
:
Button buttonFromStaticResource = this.TryFindResource("MyButtonResource") as Button;
但是此解決方案涉及一個字符串參數。 有什么比這更好的解決方案,以便我可以直接使用MyResource
(通過使用XAML文件中的x:Name
),而無需使用任何字符串?
如何在C#中讀取靜態資源,請檢查以下代碼
<Window x:Class="MyProject.MainWindow"
...
Title="MainWindow" Height="350" Width="525">
<Grid>
<StaticResource ResourceKey="MyButtonResource" x:Name="MyResource" />
</Grid>
</Window>
C#
var currentResources= this.Resources["MyButtonResource"];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.