<ComboBox Grid.Row="1" Grid.Column="0" Width="Auto" Name="cmbBudgetYear">
<ComboBoxItem Content="2009" />
<ComboBoxItem Content="2010" />
<ComboBoxItem Content="2011" />
<ComboBoxItem Content="2012" />
</ComboBox>
如何在后台代码中将所选项目设置为当前年份?
就像..。
cmbBudgetYear.SelectedItem = cmbBudgetYear.Items(
get the item with the Now.Year.ToString)
发布于 2019-02-28 17:20:36
在我的示例中,我使用以下命令手动添加值:
myComboBox.Items.Add("MyItem");
然后我用以下命令选择想要的那个:
myComboBox.SelectedItem = "WantedItem";
而不是:
myComboBox.SelectedValue = "WantedItem";
发布于 2016-10-04 04:14:47
在这种情况下,您应该能够简单地使用.Text()
来设置它:
cmbBudgetYear.Text = "2010";
但是,为了在更改后获得值,可能是因为我没有在所有地方设置SelectedValuePath="Content"
,或者可能是因为我没有使用SelectedValue
来设置它(以及为什么我要提到它),确定实际值变得稍微复杂一些,因为您必须在XAML中添加SelectionChanged
的事件处理程序之后执行此操作:
private void cmbBudgetYear_SelectionChanged(object sender, EventArgs e)
{
ComboBox cbx = (ComboBox)sender;
string yourValue = String.Empty;
if (cbx.SelectedValue == null)
yourValue = cbx.SelectionBoxItem.ToString();
else
yourValue = cboParser(cbx.SelectedValue.ToString());
}
需要解析器的地方是因为.SelectedValue.ToString()
会给出类似System.Windows.Controls.Control: 2010
的东西,所以你必须把它解析出来才能得到值:
private static string cboParser(string controlString)
{
if (controlString.Contains(':'))
{
controlString = controlString.Split(':')[1].TrimStart(' ');
}
return controlString;
}
至少,这是我遇到的.我知道这个问题是关于设置框的,但是以后也不能只解决设置而不讨论如何获取它,因为如果它改变了,你如何设置它将决定如何获取它。
发布于 2017-10-24 11:35:12
它对我来说很好。
ObservableCollection<OrganizationView> Organizations { get; set; }
Organizations = GetOrganizations();
await Dispatcher.BeginInvoke((Action)(() =>
{
var allOrganizationItem = new OrganizationView() { ID = 0, IsEnabled = true, Name = "(All)" }; // It is a class
Organizations.Add(allOrganizationItem);
cbOrganizations.DisplayMemberPath = "Name";
cbOrganizations.SelectedValuePath = "ID";
cbOrganizations.ItemsSource = null;
cbOrganizations.ItemsSource = Organizations; // Set data source which has all items
cbOrganizations.SelectedItem = allOrganizationItem; // It will make it as a selected item
}));
https://stackoverflow.com/questions/3391195
复制相似问题