【问题标题】:Bind XAML property to codebehind variable将 XAML 属性绑定到代码隐藏变量
【发布时间】:2020-03-19 10:10:04
【问题描述】:

我想通过我的 C# 代码在 XAML 中设置属性。 我这样做的方式,完全行不通。

XAML

<Page
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" Width="x:bind width_background" Height="x:bind height_background">
<Grid>
    <TextBox x:Name="Textbox1" Text="x:bind text_textbox1" /> 
    <Border BorderThickness="1" Height="x:bind height_border" Width="x:bind width_border"/>
</Grid>
</Page>

代码背后

namespace Test
{
  public sealed partial class MainPage : Page
  {

    public MainPage()
    {
        this.InitializeComponent();

        int height_background = 500;
        int width_background = 600;
        int height_border = 500;
        int width_border = 600;  
        string text_textbox1 = "string test"     
    }
  }
}

【问题讨论】:

  • 该属性用于绑定时需要为依赖属性。 @linindexi 说的是正确的。你检查过他的答案吗?

标签: c# uwp uwp-xaml xbind


【解决方案1】:

首先你应该定义属性。第二个是你应该把绑定快递放在{,请看代码。

    public static readonly DependencyProperty TextProperty = DependencyProperty.Register(
        "Text", typeof(string), typeof(MainPage), new PropertyMetadata(default(string)));

    public string Text
    {
        get { return (string) GetValue(TextProperty); }
        set { SetValue(TextProperty, value); }
    }

    <TextBox x:Name="Textbox1" Text="{x:Bind Text}" />

你可以在github中找到所有代码

更多关于绑定,请看Data binding overview - UWP applications

【讨论】:

    猜你喜欢
    • 2019-06-07
    • 1970-01-01
    • 2012-07-15
    • 2017-01-28
    • 1970-01-01
    • 2015-03-25
    • 1970-01-01
    • 2011-07-04
    • 2010-12-16
    相关资源
    最近更新 更多