How to link an object from one window to another control in another window in wpf? (c #)

advertisements

I would like to bind an object that already exist in one window to texts box in another windows. I have this object (car) that already bind to this window-

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

one of the fields of car is a struct I would like to bind to a new windw- I tried this but it isn't working

 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();

        }
    }

this is 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;
    }
}

and this is the binding in the 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>

for some reason this doesn't work, does any one know why?

thanks, for the answer. fields cannot be binding, only properties.


From your code I can see that Manufacturer is defined in a Struct CarType. The reason its not working is

  • Struct is a value type and binding will obtain a copy of it hence never update original object.

I suggest you change CarType to class