[英]Access Class Variable in XAML
I have a class defined as: 我有一个类定义为:
class Constants
{
public static string settingsToolTip = "Settings";
}
I want to set this string for a tooltip of a button like: 我想将此字符串设置为按钮的工具提示,例如:
<Button Name= "ButtonSettingsWindow" ToolTip="Settings" ToolTipService.ShowDuration="2000"/>
Instead of hardcoding the string "Settings" in XAML, I want it to use the string from Constants class. 我希望它不使用XAML中的字符串“ Settings”,而是使用Constants类中的字符串。 How can i do this in WPF XAML?
如何在WPF XAML中做到这一点?
You can access static members of class using x:Static markup extension in XAML. 您可以使用XAML中的x:Static标记扩展名访问类的静态成员。
<Button ToolTip="{x:Static local:Constants.settingsToolTip}"/>
Make sure you have added namespace in XAML file ( local ) where Constant class is declared: 确保在XAML文件( local )中添加了命名空间,其中声明了Constant类:
xmlns:local="clr-namespace:ActualNameSpace"
The answer you're looking for is binding. 您正在寻找的答案是绑定。
Example: 例:
Code behind: 后面的代码:
class Test
{
public string test { get { return "Settings"; } }
}
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
XAML: XAML:
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:y="clr-namespace:WpfApplication2"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<y:Test></y:Test>
</Window.DataContext>
<Grid>
<Button Content="{Binding test}"></Button>
</Grid>
The result is a button that says "Settings" :) 结果是一个显示“设置”的按钮:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.