[英]WPF How to make a custom combobox with a button inside to clear
我做了一個簡單的組合框,里面有一個刪除按鈕。 如果用戶單擊刪除按鈕,則組合框的selectedItem將為空。
這是我原來的組合框:(我知道,堆棧面板應該在按鈕內)
<TextBlock Text="ComboBox:"></TextBlock>
<ComboBox
ItemsSource="{Binding ITEMS}"
SelectedItem="{Binding Item}"
DisplayMemberPath="Description"
IsTextSearchEnabled="True"
IsEditable="False"
IsDropDownOpen="False">
</ComboBox>
<StackPanel
Orientation="Horizontal"
HorizontalAlignment="Right"
MouseEnter="GridSplitter_MouseEnter"
MouseLeave="GridSplitter_MouseLeave">
<Image
Source="../Images/clos.png"
Height="12" Width="15" Margin="0 0 20 4">
</Image>
</StackPanel>
我的問題:如何制作自定義組合框元素,這樣我就不必為要制作的每個組合框重復此代碼。 清除的值是selectedItem。
就像這樣:
<custom:ComboBoxWithClearance>
ItemsSource="{Binding ITEMS}"
SelectedItem="{Binding Item}"
DisplayMemberPath="Description"
IsTextSearchEnabled="True"
IsEditable="False"
IsDropDownOpen="False"
</custom:ComboBoxWithClearance>
您正在談論創建UserControl
您可以創建一個名為“ ComboBoxWithClearance”的UserControl
並將依賴項屬性 ( ItemsSource
, SelectedItem
)添加到此代碼的后面。
然后,您將當前的XAML移到UserControl
的標記文件中,並將這些屬性綁定到您創建的它們相應的自定義依賴項屬性:
<ComboBox DataContext="{Binding RelativeSource={RelativeSource AncestorType=UserControl}}"
ItemsSource="{Binding ItemsSource}"
SelectedItem="{Binding SelectedItem}"
... />
完成此操作后,您將可以在其他視圖中使用控件並將其依賴項屬性設置/綁定到所需的任何對象,例如:
<local:ComboBoxWithClearance
ItemsSource="{Binding ITEMS}"
SelectedItem="{Binding Item}">
...
</custom:ComboBoxWithClearance>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.