访问XAML中的代码隐藏变量

Mur*_*rat 48 c# silverlight wpf xaml

如何访问Sample.xaml.cs文件中的公共变量,如asp.net <%=VariableName%>

Rob*_*nee 64

有几种方法可以做到这一点.


yos*_*rel 24

对于绑定,如果DataContext没有使用,你可以简单地将它添加到后面代码的构造函数中:

this.DataContext = this;
Run Code Online (Sandbox Code Playgroud)

使用此代码,代码中的每个属性都可以绑定:

<TextBlock Text="{Binding PropertyName}"/>
Run Code Online (Sandbox Code Playgroud)

另一种方法是给XAML的根元素命名:

x:Name="root"
Run Code Online (Sandbox Code Playgroud)

由于XAML被编译为代码隐藏的部分类,因此我们可以按名称访问每个属性:

<TextBlock Text="{Binding ElementName="root" Path=PropertyName}"/>
Run Code Online (Sandbox Code Playgroud)

注意:访问仅适用于属性; 不到田地.set;和/ get;或是{Binding Mode = OneWay}必要的.如果使用OneWay绑定,则基础数据应实现INotifyPropertyChanged.


Phi*_*ice 9

对于WPF中的快速和脏Windows,我更喜欢将Window的DataContext绑定到窗口本身; 这一切都可以在XAML中完成.

Window1.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>
Run Code Online (Sandbox Code Playgroud)

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";
    }
}
Run Code Online (Sandbox Code Playgroud)

在上面的示例中,请注意DataContextWindow上属性中使用的绑定,这表示"将数据上下文设置为自己".两个文本块绑定到,MyProperty1并且MyProperty2按钮的事件处理程序将设置这些值,这些值将自动传播到Text两个TextBlock 的属性,因为属性是依赖项属性.