在 XAML 中访问代码隐藏变量 [英] Access codebehind variable in XAML
问题描述
如何访问 Sample.xaml.cs 文件中的公共变量,例如 asp.net <%=VariableName%>
?
How can I access the public variable which in Sample.xaml.cs file like asp.net <%=VariableName%>
?
推荐答案
有几种方法可以做到这一点.
There are a few ways to do this.
将您的变量添加为代码隐藏的资源:
Add your variable as a resource from codebehind:
myWindow.Resources.Add("myResourceKey", myVariable);
然后您可以从 XAML 访问它:
Then you can access it from XAML:
<TextBlock Text="{StaticResource myResourceKey}"/>
如果您必须在解析 XAML 后添加它,您可以使用上面的 DynamicResource
而不是 StaticResource
.
If you have to add it after the XAML gets parsed, you can use a DynamicResource
above instead of StaticResource
.
使变量成为 XAML 中某些内容的属性.通常这通过 DataContext
起作用:
Make the variable a property of something in your XAML. Usually this works through the DataContext
:
myWindow.DataContext = myVariable;
或
myWindow.MyProperty = myVariable;
此后,您的 XAML 中的任何内容都可以通过 Binding
访问它:
After this, anything in your XAML can access it through a Binding
:
<TextBlock Text="{Binding Path=PropertyOfMyVariable}"/>
或
<TextBlock Text="{Binding ElementName=myWindow, Path=MyProperty}"/>
这篇关于在 XAML 中访问代码隐藏变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!