[英]WPF combobox binding placeholder item
我正在嘗試將“假”項目添加到綁定到組合框的源列表中。
<Window ...
DataContext="{Binding Source={x:Static local:Singleton.Instance}}">
...
<ComboBox ItemsSource="{Binding MyList}">
-
public List<Object> MyList{ get; private set; }
我希望有一個“添加新”作為不屬於MyList的組合框項目,因為我只需要在其中包含適當的對象即可。 如果我嘗試以編程方式添加它,則會引發異常,因為無法以這種方式編輯源。
將以下內容添加到您的XAML中
IsEditable="True"
Text="Add New"
注意 :如果用戶選擇綁定值之一,則他們將無法“返回”並選擇“添加新”,因為它將不再顯示。 同樣,既然控件是可編輯的,則在執行任何處理之前,您將需要先驗證內容,以避免用戶輸入錯誤值而導致的潛在錯誤。
HappyNomad通過修改Combobox.Template
在https://stackoverflow.com/a/4053371/5188233中提供了僅xaml的解決方案。 在此建議中,您不需要操縱帶有偽造物品的貨源清單並保持其清潔。
<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.