在下面的xaml片段中,SessoList是一个字符串列表(" M"和" F")。
<ComboBox IsEditable="False" Margin="5" SelectedValue="{Binding Sesso}" ItemsSource="{Binding SessoList}" Width="40" Height="28"/>
组合框按预期工作,它是预先填充的,反映了视图模型中Sesso的值。
组合框可选择的项目只有两个并且已修复,因此我尝试在xaml中简化它们的定义:
<ComboBox IsEditable="False" Margin="5" SelectedValue="{Binding Sesso}" SelectedValuePath="{Binding Tag}" Width="40" Height="28" Name="Primo">
<ComboBoxItem Content="M" Tag="M" />
<ComboBoxItem Content="F" Tag="F" />
</ComboBox>
这个组合框能够更新viewmodel属性sesso,但不会预先填充正确的值。
报告了以下错误:
BindingExpression path error: 'Tag' property not found on 'object'
如何在xaml中成功定义组合框项目,并根据 SelectedValue 数据绑定显示正确的值?
忘了提及我使用.Net 4.0
答案 0 :(得分:0)
据我所知,你想在XAML中定义ComboBox ItemsSource, 这是对我有用的解决方案:
Xaml Window资源:
<Window.Resources>
<x:Array x:Key="Array" Type="{x:Type nirHelpingOvalButton:ComboObjectModel}">
<nirHelpingOvalButton:ComboObjectModel Content="M_Content" Tag="M_Tag"/>
<nirHelpingOvalButton:ComboObjectModel Content="F_Content" Tag="F_Tag"/>
</x:Array>
Xaml Combo:
<Grid>
<ComboBox IsSynchronizedWithCurrentItem="True" IsEditable="False" SelectedIndex="0" Margin="5" ItemsSource="{StaticResource Array}"
SelectedValue="{Binding Content, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
SelectedValuePath="Tag" Width="90" Height="28" Name="Primo">
<i:Interaction.Behaviors>
<nirHelpingOvalButton:CustomComboSelectionBehavior/>
</i:Interaction.Behaviors>
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Content}"></TextBlock>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox></Grid>
查看模型组合SelectedValue binded属性:
public string Content
{
get { return _content; }
set
{
_content = value;
OnPropertyChanged("Content");
}
}
列表项行为代码:
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.Loaded += OnLoaded;
}
private void OnLoaded(object sender, RoutedEventArgs e)
{
var firstItem = AssociatedObject.ItemsSource.Cast<object>().FirstOrDefault();
AssociatedObject.SelectedItem = firstItem;
}
protected override void OnDetaching()
{
base.OnDetaching();
AssociatedObject.Loaded -= OnLoaded;
}
问候