WPF Default Value (using Style Trigger) with Binding - wpf

I'm new to WPF so please bear with me. I have a ComboBox on my WPF window, the ItemSource property is bound to a List of strings property (Countries) and the SelectedItem is bound to a string property (SelectedCountry). Both of these properties are in the code behind - and I'm setting the DataContext to "this" (i.e. the Window).
The ComboBox xaml is:
<ComboBox Name="CountryComboBox"
VerticalAlignment="Center"
Width="200"
ItemsSource="{Binding Path=Countries, Mode=OneTime}"
SelectedItem="{Binding Path=SelectedCountry, Mode=TwoWay}">
</ComboBox>
I wanted to have a default "- Please Select -" option that is displayed when an item is not selected, therefore I placed the following xaml in App.xaml:
<Style TargetType="ComboBox">
<Style.Triggers>
<Trigger Property="SelectedItem" Value="{x:Null}">
<Setter Property="IsEditable" Value="true" />
<Setter Property="IsReadOnly" Value="true" />
<Setter Property="Text" Value="- Please Select -" />
</Trigger>
</Style.Triggers>
</Style>
When my window is first displayed, the combobox does have the "- Please Select -" text as expected. When I then select a value in the combobox, the SelectedCountry gets populated appropriately, but then when I assign "null" to the SelectedCountry property the combobox still has the same selected country when I'd expect it to go back to "- Please Select -". What am I doing wrong?
Thanks.

It may be a better option not to modify the ComboBox and simply overlay a TextBlock over the ComboBox when the SelectedItem is null.
Just wrap the ComboBox and a TextBlock in a Grid and set a DataTrigger on the TextBlock to check if the SelectedItem is null and toggle its Visibility
Example:
<Grid>
<ComboBox x:Name="combo" ItemsSource="{Binding Countries}" SelectedItem="{Binding SelectedItem}" />
<TextBlock x:Name="textblock" Text="- Please Select -" Margin="5,3,0,0" IsHitTestVisible="False">
<TextBlock.Style>
<Style TargetType="TextBlock">
<Setter Property="Visibility" Value="Hidden" />
<Style.Triggers>
<DataTrigger Binding="{Binding SelectedItem,ElementName=combo}" Value="{x:Null}">
<Setter Property="Visibility" Value="Visible" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
</Grid>
Result:

You need to insert a record into the Countries list that has a value of null and the name " - Please Select - ".
Alternatively I suppose you could extend the ComboBox control and write your own so that you could specify the null vale in the list without having to put a record into the Countries selection.
But of the two, it is much easier to just add a record to Countries.

Related

WPF Editable Combobox does not change SelectedValue while typing

I defined a Combobox whose SelectedValue is binded to a property on the view model VM.SelectedServiceTypeId
<ComboBox Name="ServiceTypeComboBox"
IsEditable="True"
Grid.Row="1"
Grid.Column="1"
Margin="5"
DisplayMemberPath="ServiceTypeName"
ItemsSource="{Binding ServiceTypes,Mode=TwoWay}"
SelectedValue="{Binding SelectedServiceTypeId, Mode=TwoWay}"
SelectedValuePath="ServiceTypeId"
Loaded="ServiceTypeComboBox_Loaded"
/>
The value is correctly updated when the user selects an item in the dropdown menu, but cause the combobox IsEditable the user is able to type whatever he wants that it's not a value in the ItemSource. In this case the SelectedValue does NOT change.
What I need to do is to enable a button when the SelectedValue is among those in the ItemsSource.
Do you have some hint?
Your wpf combobox has a property "Text" that contains the text input by the user. You will have to write some code to check if the entered text matches anything in your itemssource.
<Button Content="Click">
<Button.Style>
<Style TargetType="Button">
<Setter Property="IsEnabled" Value="True"/>
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=ServiceTypeComboBox, Path=SelectedValue}" Value="{x:Null}">
<Setter Property="IsEnabled" Value="False"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>

Is there a way to get the DataContext for a bound Property

Is there a way in code to get the the DataContent for the Text Property of the ComboBox defined below?
<ComboBox Height="21" Text="{Binding Path=Field1.Value}">
<ComboBox.Resources>
<Style TargetType="ComboBox">
<Setter Property="IsEnabled" Value="False" />
<Style.Triggers>
<DataTrigger Binding="{Binding Path=Field2.Value}" Value="">
<Setter Property="IsEnabled" Value="True" />
</DataTrigger>
</Style.Triggers>
</Style>
</ComboBox.Resources>
</ComboBox>
Currently the DataContext of the ComboBox is the user control in which it lives. Which makes sense because I want my Text bound to one property and my DataTrigger to be bound to another property. But I need to get the DataContext that's being bound to for the Text property.
Something like this should do it:
Binding binding = BindingOperations.GetBinding(yourComboBox, ComboBox.TextProperty);
object theDataContext = binding.Source;

Wpf Combobox selectedvalue trigger

I am trying to change the visibility with a trigger when a particular value in a combobox is selected, and I got the following XAML
<ItemsControl ItemsSource="{Binding AccessControl.Credentials}" >
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid >
<ComboBox Name="chkFieldType"
SelectedValue="{Binding Path=ValueSourceType,Converter={StaticResource enumstringConv}}"
SelectedValuePath="Tag" SelectionChanged="chkFieldType_SelectionChanged" >
<ComboBoxItem Tag="User">User</ComboBoxItem>
<ComboBoxItem Tag="SessionCredential">Field</ComboBoxItem>
<ComboBoxItem Tag="Inherit">From other Resource</ComboBoxItem>
</ComboBox>
<Border " Visibility="Hidden">
<Border.Resources>
<Style TargetType="{x:Type Border}">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=SelectedValue, ElementName=chkFieldType}" Value="Inherit">
<Setter Property="Visibility" Value="Visible" />
</DataTrigger>
</Style.Triggers>
</Style>
</Border.Resources>
<ComboBox/>
</Border>
In this case a border. The selected value is "Inherit" of type string but the border remainds hidden.
I ran into the same problem and found that you have to set the visibility property using the style only. So instead of having the initial visibility set with:
<Border Visibility="Hidden">
You should set the initial visibility using the style:
<Style TargetType="....">
<Setter Property="Visibility" Value="Hidden"/>
<Style.Triggers>
....
</Style.Triggers>
</Style>
(I know it's kinda overdue but I thought maybe someone else might run into the same problem).
Try SelectedItem.Tag or SelectedItem.Content instead of SelectedValue
Set your binding on SelectedValue, not SelectedItem.SelectedValue. The way you currently have it, it is looking for ComboBoxItem.SelectedValue, which doesn't exist
<DataTrigger Value="Inherit"
Binding="{Binding Path=SelectedValue,
Converter={StaticResource enumstringConv},
ElementName=chkFieldType}">
I think it's because you are putting the DataTrigger in Border.Resources.
Try putting the style in the window.resources, with a x:key in order to apply the style to the border.
I think that the border.resources can not access to a control "outside it's own resources context"
SelectedItem and SelectedValue are two seperate properties on the ComboBox.
Since your ComboBoxItems are all strings you can change
<DataTrigger Binding="{Binding Path=SelectedItem.SelectedValue, ElementName=chkFieldType}" Value="Inherit">
to
<DataTrigger Binding="{Binding Path=SelectedItem, ElementName=chkFieldType}" Value="Inherit">
I ended up setting the visibility manually via the code behind when the selectedItem event is fired..

WPF ComboBox that shows nothing selected when disabled (IsEnabled == false)

I'm thinking out different ways to have a WPF ComboBox show blank as if nothing is selected when IsEnabled is set to false. Like always I'm trying to do this without having to redefine the whole control template for the ComboBox which is always a struggle I have with WPF. If anybody has any solutions more elegant than redefining the whole ComboBox control template please let me know.
The reason for what I'm trying to do is I have a CheckBox that represents an "All" option and when checked it disables the ComboBox which is used to pick only a single individual item. If my CheckBox is checked it is sometimes confusing to the users to see a value remaining in the ComboBox since that value has no meaning in that state of the UI.
Another requirement is that the solution cannot modify the SelectedValue, SelectedIndex, or SelectedItem values of the ComboBox since I would like to retain the previuosly selected item in the case that the users unchecks the "All" CheckBox.
Solution based on HCL's answer:
<ComboBox IsEnabled="{Binding ElementName=myCheckBox, Path=IsChecked}"
ItemsSource="{Binding Path=MyItems}"
SelectedValue="{Binding Path=MySelectedItem}">
<ComboBox.ItemTemplate>
<DataTemplate>
<ContentControl x:Name="content" Content="{Binding MyItemDescription}" />
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=ComboBox}, Path=IsEnabled}"
Value="False">
<Setter TargetName="content"
Property="Visibility"
Value="Hidden" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
You can do something with triggers:
Try setting the ItemTemplate to an empty DataTemplate when the box is disabled. This will affect the rendering of the selected item and therefore hide it.
Another simple but not very nice solution would be to set the foreground color to the same as a background color.
I believe you can do this with a Style, rather than redefining the control template. Use a Trigger on the IsEnabled property to set the text shown in the ComboBox. Altering the SelectedItem would be my first approach, but since you don't want to do that, you may find success setting the DisplayMemberPath. Something like this (untested)...
<Style TargetType="{x:Type ComboBox}">
<Style.Triggers>
<Trigger Property="IsEnabled" Value="False">
<Trigger.Setters>
<Setter Property="DisplayMemberPath" Value="{x:Null}"/>
</Trigger.Setters>
</Trigger>
</Style.Triggers>
</Style>
Here's a style that does what you want. It employs a technique that I use all the time: a grid that contains multiple versions of the control, and data triggers that ensure that only one version is visible at any one time.
<ComboBox.Style>
<Style TargetType="ComboBox">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ComboBox">
<DockPanel>
<CheckBox x:Name="IsActive" DockPanel.Dock="Left"/>
<Grid>
<ComboBox
ItemsSource="{TemplateBinding ItemsSource}"
SelectedItem="{TemplateBinding SelectedItem}"
SelectedIndex="{TemplateBinding SelectedIndex}"
SelectedValue="{TemplateBinding SelectedValue}">
<ComboBox.Style>
<Style TargetType="ComboBox">
<Setter Property="Visibility" Value="Visible"/>
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=IsActive, Path=IsChecked}" Value="False">
<Setter Property="Visibility" Value="Collapsed"/>
</DataTrigger>
</Style.Triggers>
</Style>
</ComboBox.Style>
</ComboBox>
<ComboBox>
<ComboBox.Style>
<Style TargetType="ComboBox">
<Setter Property="Visibility" Value="Collapsed"/>
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=IsActive, Path=IsChecked}" Value="False">
<Setter Property="Visibility" Value="Visible"/>
</DataTrigger>
</Style.Triggers>
</Style>
</ComboBox.Style>
</ComboBox>
</Grid>
</DockPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ComboBox.Style>
This preserves the selected item, selected index, and selected value, just as you want. In fact, it does this a little too well; there's not actually a way of telling that the user deactivated the combo box, since there's no property on ComboBox that exposes this information. I'd probably actually implement this as a custom control derived from ComboBox that exposed the value of the check box as an IsActive property. There are lots of other ways to do it.

How to hide/show items in a stack panel?

I have a wpf-mvvm application.
In that I have follwoing...
<Combo box>
item 1
item 2
</Combo box>
<stack pnel>
<user control 1 />
<user control 1 />
</stack pnel>
If user select "item 1" from combo, i need to display "user control 1"
If user select "item 2" from combo, i need to display "user control 2"
In the viewmodel...I have an IList of those two combobox items.
what is the best way to hid/show items here ?
You can actually remove the StackPanel completely, as you'll only be showing one UserControl at a time.
Once you've done that, you can use the technique described here to bind the ComboBox's value to the visibility of the UserControl. Just set the Visibility to Collapsed for the UserControl that's not chosen.
This allows you to handle this completely in XAML.
There is always one more way to do it :-)
For example, you can do the very simple way: subscribe to SelectionChanged, check which is the currently selected item, and set the visibility of the items-to-be-hidden to collapsed.
There are more advanced ways, but I doubt that they are needed for this simple task. However, with the development of your code you might need to reconsider using this approach.
This demonstrates two simple ways in which you can use a style to change the visibility on elements based on the selection in a combo box. The first style checks the SelectedIndex of the combo box, and the second checks its SelectedValue. I've populated the combo box with string objects in this example, but you can use SelectedValue with any kind of object, so long as you know what its ToString() method returns.
<Page
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:system="clr-namespace:System;assembly=mscorlib">
<DockPanel>
<ComboBox x:Name="comboBox" DockPanel.Dock="Top">
<system:String>Item 1</system:String>
<system:String>Item 2</system:String>
</ComboBox>
<TextBlock DockPanel.Dock="Top" Text="This displays if Item 1 is selected">
<TextBlock.Style>
<Style TargetType="TextBlock">
<Setter Property="Visibility" Value="Collapsed"/>
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=comboBox, Path=SelectedIndex}" Value="0">
<Setter Property="Visibility" Value="Visible"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
<TextBlock DockPanel.Dock="Top" Text="This displays if Item 2 is selected.">
<TextBlock.Style>
<Style TargetType="TextBlock">
<Setter Property="Visibility" Value="Collapsed"/>
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=comboBox, Path=SelectedValue}" Value="Item 2">
<Setter Property="Visibility" Value="Visible"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
</DockPanel>
</Page>

Resources