簡體   English   中英

將TextBox文本綁定到文件后面代碼中的屬性

[英]Binding TextBox Text to property in code behind file

我有一個UserControl文件,其中有一個文本框,我想將其綁定到文件后面代碼中的屬性,但是由於某種原因,我無法使其綁定。 有人可以告訴我我在做什么錯。 提前致謝。

XAML:

<ContentDialog  Width="200" Height="400" Background="White" Padding="-40,-20" x:Name="addGreetingDialog" PrimaryButtonText="Save" SecondaryButtonText="Cancel" PrimaryButtonClick="addGreetingDialog_PrimaryButtonClick">


    <Grid Margin="-25,0,-25,0">
        <Grid.RowDefinitions>
            <RowDefinition Height="50"></RowDefinition>
            <RowDefinition Height="40"></RowDefinition>
            <RowDefinition Height="40"></RowDefinition>
        </Grid.RowDefinitions>

        <Border Grid.Row="0">
            <Border.Background>
                <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                    <GradientStop Color="#FF686868" Offset="0"/>
                    <GradientStop Color="#FF515151" Offset="1"/>
                    <GradientStop Color="#FF676767" Offset="0.5"/>
                </LinearGradientBrush>
            </Border.Background>
            <TextBlock HorizontalAlignment="Center" FontSize="24" Foreground="White"  FontFamily="ms-appx:/Assets/Fonts/Roboto-Light.ttf#Roboto"
                       Margin="10">Add Greetings</TextBlock>
        </Border>
        <TextBox Grid.Row="2" PlaceholderText="Greeting" Text="{Binding NewGreeting, Mode=TwoWay}"></TextBox>
    </Grid>
</ContentDialog>

背后的代碼:

 private string _newGreeting;
 public string NewGreeting { get { return _newGreeting; } set { _newGreeting = value; } }

 public AddGreeting()
 {

     this.InitializeComponent();
 }

 private async void addGreetingDialog_PrimaryButtonClick(global::Windows.UI.Xaml.Controls.ContentDialog sender, global::Windows.UI.Xaml.Controls.ContentDialogButtonClickEventArgs args)
 {
 }

只是更新

     public AddGreeting()
 {

     this.InitializeComponent();
 }

 public AddGreeting()
 {

     this.InitializeComponent();
     DataContext = this;
 }

這個: DataContext = this; 將告訴表單在AddGreeting類中查找指定的屬性,我想這是NewGreeting屬性所在的位置。 如果沒有,讓我們舉個例子:

    public class YourClass
    {
        private string _newGreeting;
        public string NewGreeting { get { return _newGreeting; } set { _newGreeting = value; } }

        public YourClass()
        {
            NewGreeting = "Test";
        }
    }

這樣,您將必須將DataContext設置為CodeBehind形式,如下所示: DataContext = new YourClass(); 而不是DataContext = this; 這樣,您就告訴表單在YourClass類而不是AddGreeting類中查找屬性。

有關更多信息,建議您閱讀本教程

我想到了。 我錯過了這一行。

DataContext="{Binding RelativeSource={RelativeSource Self}}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM