使用this爲出發點:
private void SetSelectedComboBoxItem(string itemName)
{
ComboItem selected = MyComboItems.FirstOrDefault(i => i.Name.Equals(itemName));
if (selected != null)
{
combo.SelectedItem = selected;
}
else
{
combo.SelectedItem = combo.Items[0];
}
}
OR
private void SetSelectedComboBoxItem(string itemName)
{
ComboItem selected = MyComboItems.FirstOrDefault(i => i.Name.Equals(itemName));
if (selected != null)
{
SelectedItem = selected;
}
else
{
SelectedItem = combo.Items[0];
}
}
然後修改您的ComboItem類包括您所使用的着色性能:
public class ComboItem
{
public string Color { get; private set; }
public SolidColorBrush BackgroundColor { get; private set; }
public SolidColorBrush ForegroundColor { get; private set; }
public ComboItem(string color, SolidColorBrush background, SolidColorBrush foreground)
{
Color = color;
BackgroundColor = background;
ForegroundColor = foreground;
}
}
和變化您的列表初始化以包含新屬性:
List<ComboItem> _myComboItems= new List<ComboItem>()
{
new ComboItem("White", Brushes.White, Brushes.Black),
new ComboItem("Gray", Brushes.Gray, Brushes.White),
new ComboItem("Dark Gray", Brushes.DarkGray, Brushes.White),
new ComboItem("Black", Brushes.Black, Brushes.White),
new ComboItem("Yellow", Brushes.Yellow, Brushes.Black),
new ComboItem("Blue", Brushes.Blue, Brushes.Black),
new ComboItem("Pink", Brushes.Pink, Brushes.Black)
};
和修改XAML中已經應用到組合框的樣式類似下面的(這將適用於所有組合框控件在做這樣的應用程序):
<Window.Resources>
<Style TargetType="{x:Type ComboBoxItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ComboBoxItem}">
<Border Name="Border"
Height="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ComboBox}}, Path=ActualHeight}"
Background="{Binding BackgroundColor}"
BorderBrush="Transparent">
<Grid>
<TextBlock x:Name="ItemText"
TextAlignment="Left"
VerticalAlignment="Center"
Text="{Binding Color}"
Margin="5,0,0,0"
Foreground="{Binding ForegroundColor}"/>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
希望我沒有錯過任何東西。
您需要使用該字符串來標識ItemSource(組合框項目)中的哪個對象是成爲選定項目的對象。即cboColors.SelectedItem = cboColors.Items.FirstOrDefault(item => item.Content.Equals(「Yellow」)); – CodexNZ
@CodexNZ它給出錯誤,「ItemCollection不包含'FirstOrDefault'的定義」。 –
爲什麼你回到硬編碼的XAML對象而不是類來表示組合中的項目?答案在這裏提供:https://stackoverflow.com/questions/45703106/pass-combobox-selected-item-as-method-parameter/45703484#45703484將允許您使用綁定收集作爲您的查找的來源,而不是需要做你正在嘗試的東西。您需要做的就是爲您的ComboItem類添加屬性,以實現後臺和前臺綁定。 – CodexNZ