C# 在 XAML 中访问代码隐藏变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/666856/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Access codebehind variable in XAML
提问by Murat
How can I access the public variable which in Sample.xaml.csfile like asp.net <%=VariableName%>
?
如何访问Sample.xaml.cs文件(如 asp.net)中的公共变量<%=VariableName%>
?
采纳答案by Robert Macnee
There are a few ways to do this.
有几种方法可以做到这一点。
Add your variable as a resource from codebehind:
myWindow.Resources.Add("myResourceKey", myVariable);
Then you can access it from XAML:
<TextBlock Text="{StaticResource myResourceKey}"/>
If you have to add it after the XAML gets parsed, you can use a
DynamicResource
above instead ofStaticResource
.Make the variable a property of something in your XAML. Usually this works through the
DataContext
:myWindow.DataContext = myVariable;
or
myWindow.MyProperty = myVariable;
After this, anything in your XAML can access it through a
Binding
:<TextBlock Text="{Binding Path=PropertyOfMyVariable}"/>
or
<TextBlock Text="{Binding ElementName=myWindow, Path=MyProperty}"/>
从代码隐藏将您的变量添加为资源:
myWindow.Resources.Add("myResourceKey", myVariable);
然后你可以从 XAML 访问它:
<TextBlock Text="{StaticResource myResourceKey}"/>
如果您必须在解析 XAML 后添加它,您可以使用
DynamicResource
上面的而不是StaticResource
.使变量成为 XAML 中某些内容的属性。通常这通过
DataContext
:myWindow.DataContext = myVariable;
或者
myWindow.MyProperty = myVariable;
在此之后,您的 XAML 中的任何内容都可以通过以下方式访问它
Binding
:<TextBlock Text="{Binding Path=PropertyOfMyVariable}"/>
或者
<TextBlock Text="{Binding ElementName=myWindow, Path=MyProperty}"/>
回答by Phil Price
For quick-and-dirty Windows in WPF, I prefer binding the DataContext of the Window to the window itself; this can all be done in XAML.
对于 WPF 中的快速和肮脏的 Windows,我更喜欢将 Window 的 DataContext 绑定到窗口本身;这一切都可以在 XAML 中完成。
Window1.xaml
窗口1.xaml
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
DataContext="{Binding RelativeSource={RelativeSource self}}"
Title="Window1" Height="300" Width="300">
<StackPanel>
<TextBlock Text="{Binding Path=MyProperty1}" />
<TextBlock Text="{Binding Path=MyProperty2}" />
<Button Content="Set Property Values" Click="Button_Click" />
</StackPanel>
</Window>
Window1.xaml.cs
Window1.xaml.cs
public partial class Window1 : Window
{
public static readonly DependencyProperty MyProperty2Property =
DependencyProperty.Register("MyProperty2", typeof(string), typeof(Window1), new UIPropertyMetadata(string.Empty));
public static readonly DependencyProperty MyProperty1Property =
DependencyProperty.Register("MyProperty1", typeof(string), typeof(Window1), new UIPropertyMetadata(string.Empty));
public Window1()
{
InitializeComponent();
}
public string MyProperty1
{
get { return (string)GetValue(MyProperty1Property); }
set { SetValue(MyProperty1Property, value); }
}
public string MyProperty2
{
get { return (string)GetValue(MyProperty2Property); }
set { SetValue(MyProperty2Property, value); }
}
private void Button_Click(object sender, RoutedEventArgs e)
{
// Set MyProperty1 and 2
this.MyProperty1 = "Hello";
this.MyProperty2 = "World";
}
}
In the above example, note the binding used in the DataContext
property on the Window, this says "Set your data context to yourself". The two text blocks are bound to MyProperty1
and MyProperty2
, the event handler for the button will set these values, which will automatically propagate to the Text
property of the two TextBlocks as the properties are Dependency Properties.
在上面的示例中,请注意DataContext
Window 上的属性中使用的绑定,这表示“将您的数据上下文设置为您自己”。两个文本块绑定到MyProperty1
和MyProperty2
,按钮的事件处理程序将设置这些值,这些值将自动传播到两个文本块的Text
属性,因为这些属性是依赖属性。
回答by yossharel
For binding, if DataContext
is not in use, you can simply add this to the constructor of the code behind:
对于绑定,如果DataContext
没有使用,你可以简单地将其添加到后面代码的构造函数中:
this.DataContext = this;
Using this, every property in the code becomes accessible to binding:
使用这个,代码中的每个属性都可以被绑定访问:
<TextBlock Text="{Binding PropertyName}"/>
Another way is to just give a name to the root element of the XAML:
另一种方法是只为 XAML 的根元素命名:
x:Name="root"
Since the XAML is compiled as a partial class of the code-behind, we can access every property by name:
由于 XAML 被编译为代码隐藏的部分类,我们可以通过名称访问每个属性:
<TextBlock Text="{Binding ElementName="root" Path=PropertyName}"/>
Note: access is only available to properties; not to fields. set;
and get;
or {Binding Mode = OneWay}
are necessary. If OneWay binding is used, the underlying data should implement INotifyPropertyChanged.
注意:访问权限仅适用于属性;不是字段。set;
和get;
或是{Binding Mode = OneWay}
必要的。如果使用 OneWay 绑定,则底层数据应实现INotifyPropertyChanged。
回答by Sheridan
It is also worth noting that a 'Binding' can only be set on a DependencyProperty of a DependencyObject. If you want to set a non DependencyProperty (eg. a normal property) on an object in XAML, then you will have to use Robert's first method of using resources in the code behind.
还值得注意的是,只能在 DependencyObject 的 DependencyProperty 上设置“绑定”。如果要在 XAML 中的对象上设置非 DependencyProperty(例如,普通属性),则必须使用 Robert 在后面的代码中使用资源的第一种方法。