Reputation: 2160
Yes this question has been asked before but please read on.
In various places I've read that this is a valid way of limiting the characters of an editable ComboBox. (i.e. 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>
For some reason however this does not work for me:
I know there are other ways to do this but I want to know why the xaml above does not work for me while this does seems to work for others.
In this example I have targeted .NET 4.5 but I've tested with 4.0 and 4.6 with the same result.
Upvotes: 1
Views: 2156
Reputation: 1385
I thought I had good understanding of Templates and Styles in WPF. I was wrong. After playing with style definitions and its placement, and checking visual tree via Snoop I believe I have some kind of explanation. According to this article and this answer
So. Combobox
has ControlTemplate
. Combobox
changes its ControlTemplate
content according to IsEditable
property. ControlTemplate
is always considered as a boundary for styles, which makes sence, if you think about it. Otherwise everything in WPF would be much more fragile to styling issues. In example, if you want to apply some margin to borders you can set the style targetting border type and put in in your borders parent resources, like UserControl, Window or anything else. If ControlTemplate wouldn't stop styling "throught it", then all your controls inside this place would be messed up terribly, since pretty much all of them use borders in their templates.
Im not sure if the person, who answered this How can I set the length of entered text in a combobox? actually checked his answer.
Hope I helped.
Upvotes: 2