延續之前的擴充ComboBox使用上的方便性1

ComboBox.jpg
參考資料
https://github.com/punker76/MahApps.Metro.SimpleChildWindow/issues/69

要取出ComboBox內的TextBox,網路上找到的方法大多是
(TextBox)cb.Template.FindName("PART_EditableTextBox", cb);

但我自己測試沒成功(null),原因不明,後來在github上看到,再加一行
cb.ApplyTemplate();
成功取出TextBox

//包裝成擴充方法
static TextBox GetEditableTextBox(this ComboBox obj)
{
    obj.ApplyTemplate();
    return (TextBox)obj.Template.FindName("PART_EditableTextBox", obj);
}

//TextBox與ComboBox的對應表
Dictionary<TextBox, ComboBox> _textBoxCBMap = new Dictionary<TextBox, ComboBox>();

TextBox partTB = ComboBoxOrderBuySell.GetEditableTextBox();
partTB.GotFocus += TextBox_GotFocus;
_textBoxCBMap[partTB] = ComboBoxOrderBuySell;

//TextBox取得邏輯焦點時,開啟ComboBox的下拉式選單
void TextBox_GotFocus(object sender, RoutedEventArgs e)
{
    if (sender is TextBox tb)
    {
        if (_editableCBMap.TryGetValue(tb, out ComboBox cb))
        {
            cb.IsDropDownOpen = true;
        }
    }
}

buysell.jpg
利用TextBox取得邏輯焦點時自動開啟下拉式選單的方式,
在TextBox輸入關鍵字時,下拉式選單也會自動鎖定可能的選項,
(如上例,鍵盤輸入小寫s,即可自動帶出Sell)
能提升查找資料的方便性(尤其當ComboBox內含的資料量很多時)

創作者介紹
創作者 GNAySolution 的頭像
Yang

GNAySolution

Yang 發表在 痞客邦 留言(0) 人氣( 30 )