将TextBox文本绑定到文件后面的代码中的属性

时间:2015-12-30 17:15:09

标签: c# xaml binding

我有一个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)
 {
 }

2 个答案:

答案 0 :(得分:0)

只需更新

     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";
        }
    }

有了这个,你必须像CodeBehind一样设置DataContext:DataContext = new YourClass();而不是DataContext = this;。这样你就告诉表单在YourClass类而不是AddGreeting类中查找属性。

有关更多信息,建议您查看this tutorial

答案 1 :(得分:0)

我明白了。我错过了这一行。

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