繁体   English   中英

如何在WPF中将对象从一个窗口绑定到另一个窗口中的另一个控件? (C#)

[英]How to bind an object from one window to another control in another window in wpf? (c#)

我想将一个窗口中已经存在的对象绑定到另一个窗口中的文本框。 我有这个已经绑定到该窗口的对象(汽车),

public partial class Car_UI : Window
{
    BE.Car car = new BE.Car();//this is the object
public Car_UI()
    {
        InitializeComponent();
        this.DataContext = car;
    }
}

汽车领域之一是一种结构,我想绑定到新的windw上-我试过了,但是没有用

 private void slc_ch_cartype(object sender, SelectionChangedEventArgs e)
    {
        ComboBoxItem lbi = ((sender as ComboBox).SelectedItem as ComboBoxItem);
        if ("other" == lbi.Content.ToString())
        {
            new carType_UI(){ DataContext =car.typecar/*this is the field in car I'm tring to bind*/}.Show();

        }
    }

这是cartype

 public struct CarType
{
    public string Manufacturer;
    public  string Model;
    public  int Volume;
    public override string ToString()
    {
        string s = String.Format(
          @"Manufacturer: {0} Model: {1} Volume: {2}"
           , Manufacturer, Model, Volume);
        return s;
    }
}

这是xaml-中的绑定

<TextBox x:Name="txtbx_manf" Grid.Column="1" Grid.Row="0" HorizontalAlignment="Stretch"  VerticalAlignment="Stretch" >
        <TextBox.Text>
            <Binding Path="Manufacturer" UpdateSourceTrigger="PropertyChanged">
                <Binding.ValidationRules>
                    <local:StringRangeValidationRule MinimumLength="1" MaximumLength="50" ErrorMessage="Manufacturer is required to be at least 1 charecthers." />
                </Binding.ValidationRules>
            </Binding>
        </TextBox.Text>
    </TextBox>

由于某种原因这不起作用,有人知道为什么吗?

感谢您的回答。 字段不能绑定,只能绑定属性。

CarType结构中的属性实际上是一个字段,而不是属性,因此WPF绑定将不会绑定到该字段。

你需要:

  • 确保TextBox的DataContext是CarType对象
  • 并且您使用适当的属性,而不是字段-最好还实现INotifyPropertyChanged

从您的代码中,我可以看到在Struct CarType中定义了Manufacturer。 它不起作用的原因是

  • 结构是一个值类型,绑定将获取它的副本,因此永远不会更新原始对象。

我建议您将CarType更改为class

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM