我正在寻找将组合框中的第一项设置为默认值的可能性。
我有我的视图(XAML(与组合框:
<ComboBox ItemsSource="{Binding SiteScripts, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
SelectedValue="{Binding SelectedSiteScriptId}"
SelectedIndex="0" SelectedValuePath="Id"
DisplayMemberPath="Name" Background="AliceBlue"
Margin="5,10,10,540" Width="100" Height="50"/>
我从组合框的ItemsSource
属性中的视图模型绑定到我的列表,并且我的SelectedValue
绑定到ID
属性项:
public List<SiteCreateMachineScripts> SiteScripts
{
get { return _siteScripts; }
set
{
_siteScripts = value;
NotifyOfPropertyChange();
}
}
public int SelectedSiteScriptId
{
get { return _selectedSiteScriptId; }
set
{
_selectedSiteScriptId = value;
NotifyOfPropertyChange();
}
}
我已经尝试设置SelectedIndex = 0
,但它不起作用
谢谢你的建议:(
如前所述,您应该在ViewModel中做得更好。
从技术上讲,您可以使用样式和Load
事件来设置SelectedIndex=0
,此时Binding
应该已经完成了ViewModel中的值设置,因此您可以设置新值:
<ComboBox ItemsSource="{Binding SiteScripts, UpdateSourceTrigger=PropertyChanged}"
SelectedValue="{Binding SelectedSiteScriptId}"
SelectedValuePath="Id"
DisplayMemberPath="Name" Background="AliceBlue"
Margin="5,10,10,540" Width="100" Height="50"/>
<ComboBox.Style>
<Style TargetType="{x:Type ComboBox}">
<Style.Triggers>
<EventTrigger RoutedEvent="Loaded">
<BeginStoryboard>
<Storyboard>
<Int32Animation Storyboard.TargetProperty="SelectedIndex" To="0"/>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Style.Triggers>
</Style>
</ComboBox.Style>
</ComboBox>
默认情况下选择常规处理
public class ViewModel
{
public List<SiteCreateMachineScripts> SiteScripts
{
get { return _siteScripts; }
set
{
_siteScripts = value;
NotifyOfPropertyChange();
}
}
public int SelectedSiteScriptId
{
get { return _selectedSiteScriptId; }
set
{
_selectedSiteScriptId = value;
NotifyOfPropertyChange();
}
}
public ViewModel()
{
SiteScripts = GetList(); // init list
SelectedSiteScriptId = SiteScripts.First().Id;
}
}