简体   繁体   English

访问 XAML 中的代码隐藏变量

[英]Access codebehind variable in XAML

How can I access the public variable which in Sample.xaml.cs file like asp.net <%=VariableName%> ?如何访问Sample.xaml.cs文件中的公共变量,例如 asp.net <%=VariableName%>

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:然后您可以从 XAML 访问它:

     <TextBlock Text="{StaticResource myResourceKey}"/>

    If you have to add it after the XAML gets parsed, you can use a DynamicResource above instead of StaticResource .如果您必须在 XAML 被解析后添加它,您可以使用上面的DynamicResource而不是StaticResource

  • Make the variable a property of something in your XAML.使变量成为 XAML 中某物的属性。 Usually this works through the DataContext :通常这通过DataContext起作用:

     myWindow.DataContext = myVariable;

    or或者

    myWindow.MyProperty = myVariable;

    After this, anything in your XAML can access it through a Binding :在此之后,您的 XAML 中的任何内容都可以通过Binding访问它:

     <TextBlock Text="{Binding Path=PropertyOfMyVariable}"/>

    or或者

    <TextBlock Text="{Binding ElementName=myWindow, Path=MyProperty}"/>

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 被编译为代码隐藏的部分 class,我们可以通过名称访问每个属性:

<TextBlock Text="{Binding ElementName="root" Path=PropertyName}"/>

Note: access is only available to properties;注意:访问仅适用于属性; not to fields.不去田野。 set; and get;get; or {Binding Mode = OneWay} are necessary.{Binding Mode = OneWay}是必需的。 If OneWay binding is used, the underlying data should implement INotifyPropertyChanged .如果使用 OneWay 绑定,则底层数据应实现INotifyPropertyChanged

For quick-and-dirty Windows in WPF, I prefer binding the DataContext of the Window to the window itself;对于 WPF 中的快速和肮脏的 Windows,我更喜欢将 Window 的 DataContext 绑定到 Z05ZB8C74CBD96FBAFDE4 本身; this can all be done in XAML.这都可以在 XAML 中完成。

Window1.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>

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".在上面的示例中,请注意 Window 上的DataContext属性中使用的绑定,这表示“将您的数据上下文设置为您自己”。 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.两个文本块绑定到MyProperty1MyProperty2 ,按钮的事件处理程序将设置这些值,这些值将自动传播到两个 TextBlocks 的Text属性,因为属性是依赖属性。

It is also worth noting that a 'Binding' can only be set on a DependencyProperty of a DependencyObject.还值得注意的是,“绑定”只能在 DependencyObject 的 DependencyProperty 上设置。 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.如果您想在 XAML 中的 object 上设置非 DependencyProperty(例如普通属性),那么您将不得不使用 Robert 在后面的代码中使用资源的第一种方法。

myWindow.xaml

<Window
    ...
    <TextBlock Text="{ Binding Path=testString }" />
</Window>

myWindow.xaml.cs

public partial class myWindow: Window
{
    public string testString { get; set; } = "This is a test string";

    public myWindow()
    {
        DataContext = this;
        InitializeComponent();
    }
}

Important重要的

  • Set Datacontext设置Datacontext
  • testString MUST be public testString必须public
  • testString MUST be a property (have a get and set ) testString必须是一个property (有一个getset

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将 XAML 属性绑定到代码隐藏变量 - Bind XAML property to codebehind variable 从 CodeBehind 访问 DataTemplate 中的 XAML 控件? - Access XAML Control In DataTemplate From CodeBehind? 我可以在代码背后的数组中访问XAML元素吗? - Can I access XAML elements in an array in the codebehind? 如何在代码隐藏中访问在XAML中创建的DataContext类实例? - How to access DataContext class instance created in XAML in codebehind? 尝试从代码隐藏中按名称访问xaml“ local:”控件时出错 - Error trying to access xaml “local:” control by name from codebehind 可以从代码隐藏全局访问任何XAML窗口对象吗? - Possible to access any XAML Window Object globally from codebehind? 在代码隐藏中初始化一些静态资源,并可以在XAML(WPF)中访问它们 - Init some static resources in codebehind and have access to them in XAML (WPF) 当背后的代码包含IValueConverter实现时,如何在XAML中访问Converter - How to access a Converter in XAML when the codebehind contains the IValueConverter implementation 无法访问aspx页面中javascript中的codebehind变量 - Unable to access codebehind variable in javascript in the aspx page 在asp.net codebehind中访问javascript变量 - access javascript variable in asp.net codebehind
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM