我将我的代码附加到XAML和C#,但它不起作用。请指教。感谢
enter code here
<Grid x:Name="LayoutRoot" Background="White">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"></ColumnDefinition>
<ColumnDefinition Width="*"></ColumnDefinition>
<ColumnDefinition Width="4*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="0.7*"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="0.7*"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="5*"></RowDefinition>
</Grid.RowDefinitions>
<TextBlock Text="Select Country" Grid.Row="0" Grid.Column="0"></TextBlock>
<ComboBox x:Name="CmbxCountry" SelectionChanged="CmbxCountry_SelectionChanged" Grid.Row="0" Grid.Column="1"></ComboBox>
<TextBlock Text="Select State" Grid.Row="2" Grid.Column="0"></TextBlock>
<ComboBox x:Name="CmbxState" Grid.Row="2" Grid.Column="1"></ComboBox>
</Grid>
命名空间Survey_Model { public partial class MainPage:UserControl { // private Brush _selectedBrush = new SolidColorBrush(Color.FromArgb(255,255,0,0)); // private Brush _normalBrush = new SolidColorBrush(Color.FromArgb(255,0,0,0));
public MainPage()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(MainPage_Loaded);
}
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
List<Country> list = new List<Country>
{
new Country{ Name = "USA" },
new Country{ Name = "China"},
new Country{States = GetStates()}
};
CmbxCountry.ItemsSource = list;
CmbxCountry.DisplayMemberPath = "Name";
}
private List<State> GetStates()
{
List<State> list = new List<State>
{
new State{ Name = "NJ" },
new State{ Name = "NY" },
new State{ Name = "NV" },
new State{ Name = "CT" },
new State{ Name = "CA" }
};
return list;
}
private void CmbxCountry_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var cmbx = sender as ComboBox;
var selectedItem = cmbx.SelectedItem as Country;
CmbxState.ItemsSource = selectedItem.States;
CmbxState.DisplayMemberPath = "Name";
}
}
public class Country
{
public string Name { get; set; }
public List<State> States { get; set; }
}
public class State
{
public string Name { get; set; }
}
}
答案 0 :(得分:0)
适合我。虽然我想你在第一个组合框中设置了错误的项目。目前,您的“国家”组合框中充满了以下国家:“美国”,“中国”,“”。每当您选择第三个(“”)时,您将获得非空状态列表。
如果您希望在当前实施中为每个国家/地区设置状态,我建议您:
List<Country> list = new List<Country>
{
new Country{ Name = "USA", States = GetStates() },
new Country{ Name = "China", States = new List<State>() },
};
而且,我建议将其重构为带有绑定的MVVM,其模型包含所选国家/地区并相应地更新第二个组合框值:
public class MainViewModel : INotifyPropertyChanged
{
private Country _selectedCountry;
public ObservableCollection<Country> Countries { get; }
public Country SelectedCountry
{
get { return _selectedCountry; }
set { _selectedCountry = value; RaisePropertyChanged("SelectedCountry"); RaisePropertyChanged("States"); }
}
public State[] States
{
get
{
if (_selectedCountry == null)
return new State[0];
return _selectedCountry.States.ToArray();
}
}
}
您的视图(xaml)不必定义事件并仅使用绑定。