2015-09-17 61 views
0

是的,這個問題以前曾被問過,但請繼續閱讀。限制可編輯組合框的輸入長度

在我讀過的各種地方,這是限制可編輯ComboBox的字符的有效方法。 (即How can I set the length of entered text in a combobox?

<Window x:Class="PlaygroundWPF.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
     xmlns:local="clr-namespace:PlaygroundWPF" 
     mc:Ignorable="d" 
     Title="MainWindow" Height="350" Width="525"> 
    <Grid> 
     <StackPanel> 
      <TextBox Width="200" Margin="5" MaxLength="10" /> 
      <ComboBox Name="comboBox" Width="200" Margin="5" IsEditable="True"> 
       <ComboBox.Resources> 
        <Style TargetType="{x:Type TextBox}"> 
         <Setter Property="MaxLength" Value="10"/> 
        </Style> 
       </ComboBox.Resources> 
      </ComboBox> 
     </StackPanel> 

    </Grid> 
</Window> 

出於某種原因,但是這並沒有爲我工作:

enter image description here

我知道還有其他方法可以做到這一點,但我想知道爲什麼上面的XAML不不適合我,雖然這似乎爲別人工作。

在這個例子中,我定位了.NET 4.5,但我用4.0和4.6測試了相同的結果。

+0

不適用於我或者 – netaholic

+0

您可以在下面找到幾種工作方法:http://stackoverflow.com/questions/1572887/how-to-set-maxlength-for-combobox-in-wpf 單程是修改控件模板並明確將MaxLength設置爲EditableTextBox。 –

+0

看看這裏https://social.msdn.microsoft.com/Forums/vstudio/en-US/55bed8e9-03ef-41a7-b2a5-3b203f40d11c/maxlength-for-editable-combobox – Sasha

回答

0

我以爲我對WPF中的Templates和Styles有很好的理解。我錯了。 玩過樣式定義及其位置,並通過Snoop檢查視覺樹後,我相信我有某種解釋。 根據this articlethis answer

所以, ComboboxControlTemplateCombobox根據IsEditable屬性更改其ControlTemplate內容。 ControlTemplate總是被認爲是風格的邊界,如果你仔細想想,它會讓你感覺很自然。否則,WPF中的所有內容對於樣式問題將更加脆弱。在例子中,如果你想爲邊界應用一些邊距,你可以設置樣式目標邊界類型,並把你的邊界放在父資源中,比如UserControl,Window或者其他東西。如果ControlTemplate不能停止樣式「穿透它」,那麼這個地方內的所有控件都會非常糟糕,因爲幾乎所有的控件都在其模板中使用邊框。

林不知道這個人,誰回答這個How can I set the length of entered text in a combobox?實際上檢查了他的答案。

希望我幫了忙。

+0

你是對的。給定的解決方案不適用於默認的組合框。 –