Есть ComboBox с двумя параметрами. Требуется чтобы в нем по default уже стояло одно из значений. Параметр SelectedIndex установлен, но ComboBox все равно загружается без default значения.
<ComboBox Name="StatusAssetClass"
Background="White"
Height="45"
HorizontalAlignment="Stretch"
Margin="16,10,16,10"
SelectedIndex="0"
ItemsSource="{x:Bind Status, Mode=OneWay}"
Style="{StaticResource ValidatableComboBoxStyle}"
SelectedItem="{x:Bind SelectedStatus, Mode=TwoWay}">
<ComboBoxItem>Active</ComboBoxItem>
<ComboBoxItem>Inactive</ComboBoxItem>
</ComboBox>
Создадим такую ViewModel
public class MainPageViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private readonly IMainPage _mainPage;
//ctor
public MainPageViewModel(IMainPage mainPage)
{
_mainPage = mainPage ?? throw new ArgumentNullException(nameof(mainPage));
}
/// <summary>
/// Содержимое комбобокса
/// </summary>
public List<string> StatusList { get; set; } = new List<string> { "Active", "Inactive" };
/// <summary>
/// Индекс выбранного в комбобоксе
/// </summary>
private int _SelectedIndexStatus;
public int SelectedIndexStatus
{
get { return _SelectedIndexStatus; }
set
{
_SelectedIndexStatus = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(SelectedIndexStatus)));
}
}
/// <summary>
/// Кнопка ОК
/// </summary>
public DelegateCommand ButtonOKCommand => new DelegateCommand(OnButtonOK);
private void OnButtonOK()
{
_mainPage.ShowMessage($"Вы выбрали: {StatusList[SelectedIndexStatus]}");
}
}
Такой кодбихайнд
public interface IMainPage
{
void ShowMessage(string message);
}
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page, IMainPage
{
public MainPage()
{
this.InitializeComponent();
//привязка ViewModel
var vm = new MainPageViewModel(this);
this.DataContext = vm;
}
public async void ShowMessage(string message)
{
var messageDialog = new MessageDialog(message);
await messageDialog.ShowAsync();
}
}
XAML такой
<ComboBox HorizontalAlignment="Left"
Margin="100,0,0,0"
Grid.Row="1"
VerticalAlignment="Center"
Width="152"
ItemsSource="{Binding StatusList}"
SelectedIndex="{Binding SelectedIndexStatus, Mode=TwoWay}"/>
<Button Content="OK"
Margin="100,0,0,0"
Grid.Row="2"
VerticalAlignment="Center"
Command="{Binding ButtonOKCommand, Mode=OneTime}"/>
<ComboBox
Name="StatusAssetClass"
Background="White"
Height="45"
HorizontalAlignment="Stretch"
Margin="16,10,16,10"
SelectedIndex="0"
Style="{StaticResource ValidatableComboBoxStyle}">
<ComboBoxItem>Active</ComboBoxItem>
<ComboBoxItem>Inactive</ComboBoxItem>
</ComboBox>
Данные получаю с ComboBox таким способом:
StatusAssetClass.SelectionBoxItem.ToString()
Сборка персонального компьютера от Artline: умный выбор для современных пользователей