我在WPF C#智能城市有一个gui 我有2个Window Forms.In第一个我有一个组合框。在第二个我有一个标签。我在第一个按钮保存我选择的组合框值并进入第二个窗口。
button_click上的代码是:
ComboBoxItem typeItem_a = (ComboBoxItem)comboBox_a.SelectedItem;
string destination_a = typeItem_a.Content.ToString();
Window1 SmartPlan2 = new Window1();
this.Hide();
SmartPlan2.ShowDialog(); // change window
现在我想在第二个窗口中自动将我保存的字符串(字符串destination_a)设置为标签。任何想法?
答案 0 :(得分:2)
@Ragavan是对的,你真的想尝试用MVVM做,这里有一个例子说明你想做什么:
<Window x:Class="double_windiwed_mvvm.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:double_windiwed_mvvm"
mc:Ignorable="d"
Title="Window1" Height="300" Width="300">
<Grid>
<ComboBox ItemsSource="{Binding Items}" SelectedItem="{Binding SelectedItem, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
HorizontalAlignment="Left" VerticalAlignment="Top" Width="120" Margin="10">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</Grid>
<Window x:Class="double_windiwed_mvvm.Window2"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:double_windiwed_mvvm"
mc:Ignorable="d"
Title="Window2" Height="300" Width="300">
<Grid>
<Label Content="{Binding SelectedItem.Name}"
HorizontalAlignment="Left" VerticalAlignment="Top" Width="120" Margin="10"/>
</Grid>
class ViewModel : INotifyPropertyChanged
{
public ObservableCollection<Person> Items { get; set; } = new ObservableCollection<Person>();
private Person _selectedItem;
public Person SelectedItem
{
get { return _selectedItem; }
set
{
if(_selectedItem != null && _selectedItem.Equals(value)) { return; }
_selectedItem = value;
PropertyChanged(this, new PropertyChangedEventArgs("SelectedItem"));
}
}
// INotifyPropertyChanged emplementation
public event PropertyChangedEventHandler PropertyChanged;
}
class Person
{
public string Name { get; set; }
}
ViewModel vm = new ViewModel();
vm.Items.Add(new Person { Name = "Bob" });
vm.Items.Add(new Person { Name = "Marie" });
vm.Items.Add(new Person { Name = "John" });
Window1 w1 = new Window1();
w1.DataContext = vm;
Window2 w2 = new Window2();
w2.DataContext = vm;
w1.Show();
w2.Show();
您可以使用窗口的DataContext指定要使用的ViewModel,如果同时为两者提供相同的ViewModel,它们将自动更新彼此。
我强烈建议你看一下MVVM&amp; amp;绑定适用于WPF。