您好我尝试为comboBox设置默认值。
XAML:
<ComboBox Name="StatusCombo"
Style="{StaticResource statusComboStyle}"
SelectedValuePath="StatusMsg"
SelectedValue="{Binding Path=SelectedStatus}"/>
我使用caliburn.Micro。我将List<string, StatusItem>
绑定到ComboBox,它运行良好。
状态项是简单类,这是:
public class StatusItem
{
public string StatusMsg { get; set; }
public BitmapImage StatusImg { get; set; }
}
App.xaml
我在app.xaml中定义了空字符串
<System:String x:Key="empty"></System:String>
statusComboStyle就在这里:
<Style x:Key="statusComboStyle" TargetType="{x:Type ComboBox}">
<Style.Triggers>
<DataTrigger Binding="{Binding Path= SelectedStatus}" Value="{StaticResource empty}">
<Setter Property="SelectedIndex" Value="0"/>
</DataTrigger>
</Style.Triggers>
</Style>
但是有些事情一定是错的,因为我得到了这个编译错误:
{"No matching constructor found on type 'System.String'. You can use the Arguments or FactoryMethod directives to construct this type."}
at System.Windows.Markup.XamlReader.RewrapException(Exception e, IXamlLineInfo lineInfo, Uri baseUri)
at System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri)
at System.Windows.Markup.WpfXamlLoader.LoadBaml(XamlReader xamlReader, Boolean skipJournaledProperties, Object rootObject, XamlAccessLevel accessLevel, Uri baseUri)
at System.Windows.Markup.XamlReader.LoadBaml(Stream stream, ParserContext parserContext, Object parent, Boolean closeStream)
at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)
at Spirit.Views.LogOnView.InitializeComponent() in c:\Users\Jan\Documents\Visual Studio 2010\Projects\C#\Pokec_Messenger\ver.beta\Pokec__Messenger\Spirit_Caliburn_Micro_v1.0\Views\LogOnView.xaml:line 1
at Spirit.Views.LogOnView..ctor() in C:\Users\Jan\Documents\Visual Studio 2010\Projects\C#\Pokec_Messenger\ver.beta\Pokec__Messenger\Spirit_Caliburn_Micro_v1.0\Views\LogOnView.xaml.cs:line 24
我检查数据触发器,如果SelectedStatus为空字符串,如果值为空字符串我在comboBox中设置frist项。
答案 0 :(得分:3)
你不需要创建自己的空字符串,字符串有一个静态字段,所以你可以用这样的样式设置它:
Value="{x:Static System:String.Empty}"
为什么不立刻使用你风格的普通二传手?
<Style x:Key="statusComboStyle" TargetType="{x:Type ComboBox}">
<Setter Property="SelectedIndex" Value="0"/>
</Style>
(您应该确保ComboBox中至少有一个项目)
答案 1 :(得分:-1)
Binding="{Binding Path=Name.Length, FallbackValue=0, TargetNullValue=0}" Value="0">