我有一个ComboBox
,其中包含一定年份。但是,我在选择该项目时遇到了麻烦。
XAML
<ComboBox MaxDropDownHeight="90" Height="10" Width="80" ItemsSource="{Binding accy}" DisplayMemberPath="DisplayMember" SelectedValuePath="ValuePath" SelectedValue="{Binding Accy_selected}"/>
MainWindow.cs
public MainWindow()
{
InitializeComponent();
this.DataContext = new Test();}
Test.cs
class Test
{
public ObservableCollection<ComboYear> accy { get; set; }
private string _accy_selected = "";
public Test()
{
int min = 1940;
int max = 2040;
accy = new ObservableCollection<ComboYear>();
for (int i = min; i < max; i++)
{
accy.Add(new ComboYear { DisplayMember = Convert.ToString(i), ValuePath = Convert.ToString(i) });
}
Accy_selected = Convert.ToString(max);
}
public class ComboYear
{
public string DisplayMember { get; set; }
public string ValuePath { get; set; }
}
public string Accy_selected
{
get { return _accy_selected; }
set
{
if (value != _accy_selected)
{
_accy_selected = value;
NotifyPropertyChanged("Accy_selected");
}
}
}
ComboBox
被填充,但是没有选择任何项目。奇怪的是,如果我更改此行
Accy_selected = Convert.ToString(max);
为此,它正在工作。 ComboBox
每年都在运行。我太傻了,无法将int
转换为string
吗?
Accy_selected = "2039";
我不知道如何解决
答案 0 :(得分:2)
max
(2040
)不包含在ComboBox
中,对吗?只要计数器变量i
小于 max
,就可以进行迭代:
for (int i = min; i < max; i++)
如果将条件更改为i <= max
,则在设置Accy_selected
属性时应包括并选择值“ 2040”:
Accy_selected = Convert.ToString(max);