【问题标题】:how to bind a textbox value from User Control to another Window in wpf?如何将用户控件中的文本框值绑定到 wpf 中的另一个窗口?
【发布时间】:2014-07-07 12:02:21
【问题描述】:

我有一个用户控件。我有一个文本框。如果我在文本框中设置任何值,然后我单击用户控件中的“选择”按钮。我想要的是,在我的窗口页面中,我有另一个文本框。我想绑定已经在用户控件文本框中选择的文本值。我有以下代码。 用户控制:

   <UserControl x:Class="Usercontrol1" x:Name="root">
   <Grid DataContext="{Binding ElementName=root}">
            <TextBox HorizontalAlignment="Right" VerticalAlignment="Center" 
               x:Name="txtAuto" TextWrapping="NoWrap" />
            <Button Name="btn_setectedType" HorizontalAlignment="Right" VerticalAlignment="Center" Content="Select"  Click="btn_setectedType_Click"/>                

   </Grid>
  </UserControl>

这是我的窗口页面..

  <Window x:Class="Window1" Title="Facility" >

      <Grid>
         <TextBox x:Name="txtUserSelection" HorizontalAlignment="Left"  Text="{Binding ???}" VerticalAlignment="Top" />
      </Grid>
 </Window>

我不知道如何继续。我尝试为此窗口创建对象并尝试直接从用户控件传递。但它失败了。我的要求是,每当我更改用户控件中的值时,该值应该绑定在窗口中的文本框上。有人可以帮忙吗?

【问题讨论】:

  • 我觉得你需要好好学习 WPF,然后再回来问问题……问题是你似乎还不够了解,甚至无法理解那些答案你已经被提供,这不是一个你可以来学习语言的网站......那是你的工作。

标签: wpf xaml user-controls


【解决方案1】:

您应该创建一个 ViewModel 来保存要在控件之间共享的属性,并将其设置为 MainWindow 和 UserControl 的 DataContext。然后你应该将这两个 TextBoxes 绑定到该属性。

ViewModel 示例:

public class MyViewModel : INotifyPropertyChanged {
    public string MyProperty {
        get { return _myProperty; }
        set { _myProperty = value; OnPropertyChanged("MyProperty");}
    }
}

并在 XAML 中使用它:

<Window [...]>
    <Window.DataContext>
         <local:MyViewModel/>
    </Window.DataContext>
    <TextBox Text="{Binding MyProperty}"/>
    <UserControl1 />

在这里,您的 UserControl1 已经将其 DataContext 设置为与 Window 相同,您可以只镜像 TextBox 中的 Binding。您没有指定创建 UserControl 的位置,所以我不能比这更具体。

【讨论】:

  • 我是 wpf 的新手。你能分享任何链接吗?或者你能为此提供一些例子吗?
  • 我已经更新了答案。如果您仍然需要详细说明,请不要犹豫。但是我在提供有效答案时缺少一个关键要素:您在哪里使用您的 UserControl1?
  • 坦率地说,我真的不明白在哪里可以使用该视图模型。我只在同一个应用程序中使用我的用户控件。
  • 您可以在 DataContext 的任何位置使用该 ViewModel。在我的示例中,这意味着您的窗口中的任何位置。 “{Binding MyProperty}”的意思是“显示设置为 DataContext 的对象的 MyProperty 属性的值”。如果您不知道 DataContext 是什么,我强烈建议您阅读 WPF 中的绑定。
【解决方案2】:

string 属性添加到您的MainWindow 代码后面:

public static readonly DependencyProperty StringValueProperty = DependencyProperty.
    Register("StringValue", typeof(string), typeof(MainWindow), 
    new UIPropertyMetadata("Some default value"));

public string StringValue
{
    get { return (string)GetValue(StringValueProperty); }
    set { SetValue(StringValueProperty, value); }
}

然后您可以使用RelativeSource Binding 将数据从您的UserControl 直接绑定到MainWindow.xaml.cs 文件中的此属性,如下所示:

<TextBox x:Name="txtUserSelection" Text="{Binding StringValue, RelativeSource={
    RelativeSource AncestorType={x:Type Window}}, Mode=TwoWay}" />

【讨论】:

  • 用户控件中的代码是什么?我有一个选择按钮。仅单击该按钮后,来自用户控件的文本值将绑定在我的主窗口中
猜你喜欢
  • 2013-01-06
  • 1970-01-01
  • 1970-01-01
  • 2014-01-26
  • 2011-09-20
  • 1970-01-01
  • 2021-11-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多