【发布时间】:2015-03-29 08:44:52
【问题描述】:
我正在尝试构建付款信息表单,但遇到了一些麻烦。
- 我有这个“国家/地区”组合框,可以让用户选择国家/地区。
- 我还有另一个“州”组合框,可让用户选择国家/地区的州。
- 由于每个国家/地区都有不同的州,ItemSource 取决于“国家/地区”组合框的选择。
XAML 的层次结构:TabControl -> 网格 -> 组合框
我还需要将数据存储在一个Profile类的实例中,调用这个profile 1(profile存储在一个静态的Observable Collection中,调用这个Profiles),程序会包含多个profile。
问题:
我很难将此绑定到 State ComboBox,因为我是 WPF 的新手,因此将不胜感激。非常感谢。
问题是我不知道如何使 State ComboBox ItemSource 有条件地绑定到 ComboBoxSource 类成员,同时与各个配置文件的 State 属性同步。 (读取字符串的值需要同步)
解决方案:
<ComboBox Name="Country" ItemsSource="{Binding Source={x:Static loc:ComboBoxItemSource.Countries}}" SelectedItem="{Binding Path=Country, Mode=TwoWay}">
<ComboBox Name="State" ItemsSource="{Binding States, Mode=TwoWay}" SelectedItem="{Binding Path=State, Mode=TwoWay}">
将此与“stijn”的解决方案结合使用,非常感谢! 出于某种原因,如果我使用“状态”组合框的原始属性,则所选选项不会在运行时显示出来。
主要思想是使用 SelectedItem 代替 SelectedValue 和 SelectedValuePath
原代码如下:
XAML:
<ComboBox Name="Country" Grid.Row="0" Grid.Column="3" SelectedValuePath="Content" SelectedValue="{Binding Country, Mode=TwoWay}" SelectionChanged="Country_SelectionChanged">
<ComboBoxItem>USA</ComboBoxItem>
<ComboBoxItem>Canada</ComboBoxItem>
<ComboBoxItem>Japan</ComboBoxItem>
</ComboBox>
<ComboBox Name="State" Grid.Row="1" Grid.Column="3" SelectedValuePath="Content" SelectedValue="{Binding State, Mode=TwoWay}" ItemsSource="{Binding Source={x:Static loc:ComboBoxItemSource.USStates}}">
代码隐藏:
class Profile
{
//default values
private string country = "Canada";
public string Country
{
get { return country; }
set
{
country = value;
this.OnPropertyChanged();
}
}
//default values
private string state = "CA2";
public string State
{
get { return state; }
set
{
state = value;
this.OnPropertyChanged();
}
}
}
public class ComboBoxItemSource
{
public static MTObservableCollection<string> USStates = new MTObservableCollection<string> { "VA", "DC" };
public static MTObservableCollection<string> CanadaStates = new MTObservableCollection<string> { "CA1", "CA2" };
public static MTObservableCollection<string> Countries = new MTObservableCollection<string> { "USA", "Canada", "Japan" };
}
//Some method in the main class:
private void Country_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Dispatcher.BeginInvoke(new Action(() =>
{
if (Profiles.Count > 0)
{
//the ComboBox is inside a grid, which is inside a TabControl that displays all the profiles
Profile item = (Profile)((Grid)((ComboBox)sender).Parent).DataContext;
ContentPresenter cp = Tabs.Template.FindName("PART_SelectedContentHost", Tabs) as ContentPresenter;
ComboBox g = Tabs.ContentTemplate.FindName("State", cp) as ComboBox;
if (g.ItemsSource == null) { return; }
if (((ComboBox)sender).Text == "USA")
{
g.ItemsSource = ComboBoxItemSource.USStates;
}
else if (((ComboBox)sender).Text == "Canada")
{
g.ItemsSource = ComboBoxItemSource.CanadaStates;
}
}
}));
}
【问题讨论】: