[英]WPF combobox binding placeholder item
I'm trying to add a "fake" item to my source list binded to a combobox. 我正在尝试将“假”项目添加到绑定到组合框的源列表中。
<Window ...
DataContext="{Binding Source={x:Static local:Singleton.Instance}}">
...
<ComboBox ItemsSource="{Binding MyList}">
-- -
public List<Object> MyList{ get; private set; }
I want to have a "Add New" as a combobox item that do not belong to MyList, since I need to have only proper objects inside it. 我希望有一个“添加新”作为不属于MyList的组合框项目,因为我只需要在其中包含适当的对象即可。 If I try to add it programmatically an exception is raised since the source cannot be edit in such a way.
如果我尝试以编程方式添加它,则会引发异常,因为无法以这种方式编辑源。
Add the following to your XAML 将以下内容添加到您的XAML中
IsEditable="True"
Text="Add New"
Caution : If the user selects one of the bound values, they cannot "go back" and select "Add New" as it will no longer appear. 注意 :如果用户选择绑定值之一,则他们将无法“返回”并选择“添加新”,因为它将不再显示。 Also, now that the control is editable, you will need to validate the content before you do any processing to avoid potential errors introduced by the user entering a bad value.
同样,既然控件是可编辑的,则在执行任何处理之前,您将需要先验证内容,以避免用户输入错误值而导致的潜在错误。
HappyNomad gives in https://stackoverflow.com/a/4053371/5188233 a xaml-only solution by modifying the Combobox.Template
. HappyNomad通过修改
Combobox.Template
在https://stackoverflow.com/a/4053371/5188233中提供了仅xaml的解决方案。 In this proposal you don't need to manipulate your sourcelist with fake items and keep them clean. 在此建议中,您不需要操纵带有伪造物品的货源清单并保持其清洁。
<ComboBox ItemsSource="{Binding MyList}" ... >
<ComboBox.Template>
<ControlTemplate TargetType="ComboBox">
<Grid>
<ComboBox x:Name="cbItems"
DataContext="{Binding RelativeSource={RelativeSource TemplatedParent}}"
ItemsSource="{Binding ItemsSource, RelativeSource={RelativeSource TemplatedParent}}"
SelectedValue ="{Binding SelectedValue, RelativeSource={RelativeSource TemplatedParent}}"
/>
<TextBlock x:Name="tbItem" Text="Add New" IsHitTestVisible="False" Visibility="Hidden"/>
</Grid>
<ControlTemplate.Triggers>
<Trigger SourceName="cbItems" Property="SelectedItem" Value="{x:Null}">
<Setter TargetName="tbItem" Property="Visibility" Value="Visible"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</ComboBox.Template>
</ComboBox>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.