WPF: ComboBox: exposing DataTemplate bindings in Style / ControlTemplate - c#

Lets say I have a sample ComboBox defined like this.
<ComboBox ItemsSource="{Binding Path=Bikes}"
HorizontalAlignment="Stretch">
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Ellipse Fill="{DynamicResource AccentColorBrush}"
Height="15"
Width="15"
VerticalAlignment="Center"/>
<TextBlock Text="{Binding Type}"
Margin="15, 0, 0, 0"
FontWeight="SemiBold"
Foreground="{DynamicResource AccentColorBrush}"
VerticalAlignment="Center"/>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
What I would like to do is to wrap it in a Style, but expose the ItemSource property of ComboBox and Text property within DataTemplate, so that I can Bind to different properties each time I use ComboBox.

I can suggest you to create a combo-box style that will select the template of its combo-item using the ViewModel-First approach. So there will be number of data-templates each of wich will relate to specific view-model.
<Window x:Class="WpfViewConstructorCall.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:local="clr-namespace:WpfViewConstructorCall"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="MainWindow"
Width="525"
Height="350"
mc:Ignorable="d">
<Window.Resources>
<!--Combo-item data-template wich is defining the final item view-->
<DataTemplate x:Key="ComboItemContentTemplate">
<StackPanel Orientation="Horizontal">
<Ellipse Width="15"
Height="15"
VerticalAlignment="Center"
Fill="GreenYellow" />
<TextBlock Margin="15, 0, 0, 0"
VerticalAlignment="Center"
FontWeight="SemiBold"
Foreground="Red"
Text="{Binding}" />
</StackPanel>
</DataTemplate>
<!--Combo-item data-template wich relates to ItemA view-model-->
<DataTemplate DataType="{x:Type local:ItemA}">
<ContentControl Content="{Binding Name}"
ContentTemplate="{StaticResource ComboItemContentTemplate}" />
</DataTemplate>
<!--Combo-item data-template wich relates to ItemB view-model-->
<DataTemplate DataType="{x:Type local:ItemB}">
<ContentControl Content="{Binding Kind}"
ContentTemplate="{StaticResource ComboItemContentTemplate}" />
</DataTemplate>
<!--Combo-item data-template wich relates to ItemC view-model-->
<DataTemplate DataType="{x:Type local:ItemC}">
<ContentControl Content="{Binding Type}"
ContentTemplate="{StaticResource ComboItemContentTemplate}" />
</DataTemplate>
<!--main Combo-item data-template-->
<DataTemplate x:Key="ComboItemDataTemplate">
<ContentControl Content="{Binding}" />
</DataTemplate>
<!--Combo style-->
<Style x:Key="ComboBoxStyle"
TargetType="ComboBox">
<Setter Property="HorizontalAlignment" Value="Stretch" />
<Setter Property="ItemTemplate" Value="{StaticResource ComboItemDataTemplate}" />
</Style>
</Window.Resources>
<Grid>
<Grid.DataContext>
<local:GridDataContext />
</Grid.DataContext>
<StackPanel>
<!--Combo(s) with specific source definition-->
<ComboBox x:Name="A"
DisplayMemberPath="Name"
ItemsSource="{Binding ItemsA}"
SelectedValuePath="Name"
Style="{StaticResource ComboBoxStyle}" />
<ComboBox x:Name="B"
DisplayMemberPath="Kind"
ItemsSource="{Binding ItemsB}"
SelectedValuePath="Kind"
Style="{StaticResource ComboBoxStyle}" />
<ComboBox x:Name="C"
DisplayMemberPath="Type"
ItemsSource="{Binding ItemsC}"
SelectedValuePath="Type"
Style="{StaticResource ComboBoxStyle}" />
</StackPanel>
</Grid></Window>
In case you will have an additional combo-item's view model you will add a data-template which will relate to that specific view-model and will define its view.
Let me knnow if you need more examples.
Best regards.

Related

WPF Data trigger to apply label and child?

i have the following xaml where if Status is OK then label background is green, and if ERROR label background in red, this works fine for the parent label, but when i add a child i also want that to adopt the parent background color? is there a way to allow the datatrigger to act for both parent and child labels ?
heres the xaml
<Window x:Class="wpfdemo.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:wpfdemo"
mc:Ignorable="d"
Title="MainWindow" Height="50" Width="50" SizeToContent="WidthAndHeight" ResizeMode="NoResize" Topmost="True" AllowsTransparency="True" WindowStyle="None" Background="Transparent">
<ItemsControl ItemsSource="{Binding Path=Parents}" Grid.IsSharedSizeScope="True">
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type local:Parent}">
<Grid>
<Grid.ContextMenu>
<ContextMenu>
<MenuItem Header="Click Me" Click="Button_Click" />
</ContextMenu>
</Grid.ContextMenu>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" SharedSizeGroup="ParentColumn" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<!-- Parent label -->
<Label Content="{Binding Path=Name}"
x:Name="Label" HorizontalAlignment="Stretch" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" BorderBrush="Black" BorderThickness="1" FontFamily="Verdana" Foreground="White"/>
<!-- Errors -->
<ItemsControl ItemsSource="{Binding Path=Errors}"
Grid.Column="1">
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type local:Child}">
<Label Content="{Binding Path=Name}"
HorizontalAlignment="Stretch" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" BorderBrush="Black" BorderThickness="1" FontFamily="Verdana" Foreground="White"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</Grid>
<DataTemplate.Triggers>
<!-- Parent is ok -->
<DataTrigger Binding="{Binding Path=Status}"
Value="OK">
<Setter TargetName="Label" Property="Background" Value="#BF008000" />
</DataTrigger>
<!-- Parent is error -->
<DataTrigger Binding="{Binding Path=Status}"
Value="ERROR">
<Setter TargetName="Label" Property="Background" Value="#BFFFFF00" />
<Setter TargetName="Label" Property="Foreground" Value="Black" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
Thanks
TargetName is control's name,not type.
try :
<DataTemplate >
<Label x:Name="ChildLabel" Content="{Binding Path=Name}"/>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding Path=DataContext.Status,RelativeSource={ RelativeSource Mode=TemplatedParent}}" Value="OK">
<Setter TargetName="ChildLabel" Property="Background" Value="#BF008000" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>

WPF: Prevent ComboBox from displaying selected item

I have a ComboBoxthat I have templated to look like this:
Here is the XAML for this ComboBox:
<ComboBox Name="StateInclusionRules_ComboBox"
ItemsSource="{Binding StateInclusionRules}"
Height="25"
Width="155"
Margin="0"
Grid.Column="7">
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal"
Margin="0">
<Label Content="{Binding State}"
Margin="0,0,0,0"
Width="30" />
<CheckBox IsChecked="{Binding StateTax}"
Margin="20,0,0,0"/>
<CheckBox IsChecked="{Binding StateChildSupport}"
Margin="30,0,0,0"/>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
Is there a way to prevent the selected item from being displayed in the ComboBox ContentPresenter (the red bordered area, i.e, the area you see when the ComboBox is closed)?
First you need 2 DataTemplates, 1 for the selected item and 1 for the drop down item.
The selected we are going to leave empty because this is your requirment.
The drop down item DataTemplate will have the exact DataTemplate you wanted.
When item is selected a DataTrigger will change it's template to the SelectedTemplate, like so:
<Window.Resources>
<DataTemplate x:Key="DropDownItemTemplate" DataType="wpfApplication1:ItemSourceModel">
<StackPanel Orientation="Horizontal"
Margin="0">
<Label Content="{Binding Value}"
Margin="0,0,0,0"
Width="30" />
<CheckBox IsChecked="{Binding Value}"
Margin="20,0,0,0"/>
<CheckBox IsChecked="{Binding Value}"
Margin="30,0,0,0"/>
</StackPanel>
</DataTemplate>
<DataTemplate x:Key="SelectionBoxTemplate">
</DataTemplate>
<DataTemplate x:Key="ComboBoxTemplate">
<ContentPresenter x:Name="Presenter"
Content="{Binding}"
ContentTemplate="{StaticResource DropDownItemTemplate}" />
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource FindAncestor,ComboBoxItem,1}}" Value="{x:Null}">
<Setter TargetName="Presenter" Property="ContentTemplate" Value="{StaticResource SelectionBoxTemplate}" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</Window.Resources>
And set your ComboBox with the ComboBoxTemplate:
<ComboBox Name="StateInclusionRules_ComboBox"
ItemsSource="{Binding YourItemSource}" ItemTemplate="{StaticResource ComboBoxTemplate}"
Height="25"
Width="155"
Margin="0"
/>

How to update TabControl resources?

I have a tab control in my view, bound to an observable collection. But when I call RaisePropertyChanged on it nothing gets updated. The tabs enabled do, but the views inside the tabs do not. How do I refresh the views in my Data templates?
<TabControl IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding DeviceListViewModel.SelectedDevice.TabViewModelsCollection, UpdateSourceTrigger=PropertyChanged}" SelectedItem="{Binding DeviceListViewModel.SelectedDevice.SelectedTabItemVm}" >
<TabControl.Resources>
<DataTemplate DataType="{x:Type vms:HomeViewModel}">
<local:HomeTab/>
</DataTemplate>
<DataTemplate DataType="{x:Type vms:ConfigurationViewModel}">
<Grid>
<local:ConfigurationFileView Visibility="{Binding Configuration, TargetNullValue=Collapsed, FallbackValue=Visible}"/>
<local:ErrorTab Visibility="{Binding Path= Configuration, TargetNullValue=Visible, FallbackValue=Hidden}"/>
</Grid>
</DataTemplate>
<DataTemplate DataType="{x:Type vms:ExpansionModulesViewModelFactory}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="35"/>
</Grid.RowDefinitions>
<StackPanel Grid.Row="0">
<DockPanel >
<local:ExpansionModulesList Title="Discovered/Enumerated"
DataContext="{Binding DiscoveredModules}"
/>
<GridSplitter Width="5"/>
<local:ExpansionModulesList Title="User Action Required"
DataContext="{Binding FaultyModules}"
/>
</DockPanel>
</StackPanel>
<DockPanel Grid.Row="1">
<StackPanel Orientation="Horizontal" FlowDirection="RightToLeft" Margin="5" IsEnabled="{Binding IsCommandEnabled}">
<Button Content="Cancel" HorizontalAlignment="Right"
Command="{Binding CancelExpansionCommand }"
ToolTip="Revert all local modifications by refreshing data from the controller." />
<Separator Width="10"/>
<Button Content="Apply" HorizontalAlignment="Center"
Command="{Binding ApplyExpansionCommand }"
ToolTip="Apply all changes to the controller." />
<Separator/>
</StackPanel>
</DockPanel>
</Grid>
</DataTemplate>
<DataTemplate DataType="{x:Type vms:LogViewModel}">
<local:LogView />
</DataTemplate>
<DataTemplate DataType="{x:Type vms:SignalStrengthViewModel}">
<local:SignalStrengthView />
</DataTemplate>
</TabControl.Resources>
<TabControl.ItemContainerStyle>
<Style TargetType="{x:Type TabItem}">
<Setter Property="Header" Value="{Binding Name}" />
<Setter Property="IsEnabled" Value="{Binding IsEnabled}" />
<Setter Property="Header" Value="{Binding Name}" />
</Style>
</TabControl.ItemContainerStyle>
<!--End Device List-->
</TabControl>
actually i can't understand why doesn't update your view, i think you must show me your behind code.
any way you can try:
tabControl.UpdateLayout();
and
tabControl.UpdateDefaultStyle();

How Does This Grid App Template Scroll without a Scrollviewer? (C#/XAML Windows 8.1)

I've been trying to understand Scrollviewers, and thought I'd take a look at Microsoft's template for a Grid App for 8.1, whose content extends off the screen. What's odd is that there doesn't seem to even be a Scrollviewer in the XAML page. Can anyone tell me what is enabling the scrolling?
<Page
x:Name="pageRoot"
x:Class="GridApp.GroupedItemsPage"
DataContext="{Binding DefaultViewModel, RelativeSource={RelativeSource Self}}"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:GridApp"
xmlns:data="using:GridApp.Data"
xmlns:common="using:GridApp.Common"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Page.Resources>
<x:String x:Key="ChevronGlyph"></x:String>
<!--
Collection of grouped items displayed by this page, bound to a subset
of the complete item list because items in groups cannot be virtualized
-->
<CollectionViewSource
x:Name="groupedItemsViewSource"
Source="{Binding Groups}"
IsSourceGrouped="true"
ItemsPath="Items"
d:Source="{Binding Groups, Source={d:DesignData Source=/DataModel/SampleData.json, Type=data:SampleDataSource}}"/>
</Page.Resources>
<!--
This grid acts as a root panel for the page that defines two rows:
* Row 0 contains the back button and page title
* Row 1 contains the rest of the page layout
-->
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid.ChildrenTransitions>
<TransitionCollection>
<EntranceThemeTransition/>
</TransitionCollection>
</Grid.ChildrenTransitions>
<Grid.RowDefinitions>
<RowDefinition Height="140"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!-- Horizontal scrolling grid -->
<GridView
x:Name="itemGridView"
AutomationProperties.AutomationId="ItemGridView"
AutomationProperties.Name="Grouped Items"
Grid.RowSpan="2"
Padding="116,137,40,46"
ItemsSource="{Binding Source={StaticResource groupedItemsViewSource}}"
SelectionMode="None"
IsSwipeEnabled="false"
IsItemClickEnabled="True"
ItemClick="ItemView_ItemClick">
<GridView.ItemTemplate>
<DataTemplate>
<Grid HorizontalAlignment="Left" Width="250" Height="250">
<Border Background="{ThemeResource ListViewItemPlaceholderBackgroundThemeBrush}">
<Image Source="{Binding ImagePath}" Stretch="UniformToFill" AutomationProperties.Name="{Binding Title}"/>
</Border>
<StackPanel VerticalAlignment="Bottom" Background="{ThemeResource ListViewItemOverlayBackgroundThemeBrush}">
<TextBlock Text="{Binding Title}" Foreground="{ThemeResource ListViewItemOverlayForegroundThemeBrush}" Style="{StaticResource TitleTextBlockStyle}" Height="60" Margin="15,0,15,0"/>
<TextBlock Text="{Binding Subtitle}" Foreground="{ThemeResource ListViewItemOverlaySecondaryForegroundThemeBrush}" Style="{StaticResource CaptionTextBlockStyle}" TextWrapping="NoWrap" Margin="15,0,15,10"/>
</StackPanel>
</Grid>
</DataTemplate>
</GridView.ItemTemplate>
<GridView.ItemsPanel>
<ItemsPanelTemplate>
<ItemsWrapGrid GroupPadding="0,0,70,0"/>
</ItemsPanelTemplate>
</GridView.ItemsPanel>
<GridView.GroupStyle>
<GroupStyle>
<GroupStyle.HeaderTemplate>
<DataTemplate>
<Grid Margin="0,0,0,2">
<Button Foreground="{ThemeResource ApplicationHeaderForegroundThemeBrush}"
AutomationProperties.Name="Group Title"
Click="Header_Click"
Style="{StaticResource TextBlockButtonStyle}" >
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Title}" Margin="0,-11,10,10" Style="{StaticResource SubheaderTextBlockStyle}" TextWrapping="NoWrap" />
<TextBlock Text="{StaticResource ChevronGlyph}" FontFamily="Segoe UI Symbol" Margin="0,-11,0,10" Style="{StaticResource SubheaderTextBlockStyle}" TextWrapping="NoWrap" />
</StackPanel>
</Button>
</Grid>
</DataTemplate>
</GroupStyle.HeaderTemplate>
</GroupStyle>
</GridView.GroupStyle>
</GridView>
<!-- Back button and page title -->
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="120"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Button x:Name="backButton" Margin="39,59,39,0" Command="{Binding NavigationHelper.GoBackCommand, ElementName=pageRoot}"
Style="{StaticResource NavigationBackButtonNormalStyle}"
VerticalAlignment="Top"
AutomationProperties.Name="Back"
AutomationProperties.AutomationId="BackButton"
AutomationProperties.ItemType="Navigation Button"/>
<TextBlock x:Name="pageTitle" Text="{StaticResource AppName}" Style="{StaticResource HeaderTextBlockStyle}" Grid.Column="1"
IsHitTestVisible="false" TextWrapping="NoWrap" VerticalAlignment="Bottom" Margin="0,0,30,40"/>
</Grid>
</Grid>
If we go check out the default GridView template and look for the ItemsPresenter we see it's embedded in a ScrollViewer at the template level. Since now we know there's one there, if we look up towards the top in the Setter declarations we've got some Properties available to us to interact with that ScrollViewer from the GridView itself by seeing;
<Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Auto"/>
<Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Disabled"/>
<Setter Property="ScrollViewer.HorizontalScrollMode" Value="Enabled" />
<Setter Property="ScrollViewer.IsHorizontalRailEnabled" Value="False" />
<Setter Property="ScrollViewer.VerticalScrollMode" Value="Disabled" />
<Setter Property="ScrollViewer.IsVerticalRailEnabled" Value="False" />
<Setter Property="ScrollViewer.ZoomMode" Value="Disabled" />
<Setter Property="ScrollViewer.IsDeferredScrollingEnabled" Value="False" />
<Setter Property="ScrollViewer.BringIntoViewOnFocusChange" Value="True" />
So if we wanted that GridView to not scroll anymore we could tell it not to like;
<GridView ScrollViewer.HorizontalScrollBarVisibility="Disabled"/>
since it's set to "Auto" at the template level by default.
That's the thing about templates, sometimes it just takes digging one level deeper. Hope this helps, cheers.

Why tooltip doesn't update it's content when binding changes?

I have written following xaml code:
<Window x:Class="WpfApplication3.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="200" Width="200">
<StackPanel>
<ListBox Name="listBox">
<ListBoxItem Content="item1" />
<ListBoxItem Content="item2" />
<ListBoxItem Content="item3" />
</ListBox>
<TextBlock DataContext="{Binding ElementName=listBox, Path=SelectedItem}" Text="{Binding Content}" ToolTip="{Binding Content}" />
<TextBlock DataContext="{Binding ElementName=listBox, Path=SelectedItem}" Text="{Binding Content}">
<TextBlock.ToolTip>
<ToolTip Content="{Binding Content}"/>
</TextBlock.ToolTip>
</TextBlock>
</StackPanel>
</Window>
Why first tooltip always has the same text as it's parent TextBlock and second never changes it's content when I change selected item in listBox?
In the second example you're setting the ToolTip of the TextBlock to be a ToolTip. So you actually set the Content of the ToolTip to be another ToolTip. These would be the same as the first.
<TextBlock DataContext="{Binding ElementName=listBox, Path=SelectedItem}" Text="{Binding Content}" ToolTip="{Binding Content}" />
<TextBlock DataContext="{Binding ElementName=listBox, Path=SelectedItem}" Text="{Binding Content}">
<TextBlock.ToolTip>
<Binding Path="Content"/>
</TextBlock.ToolTip>
</TextBlock>
And these would pretty much be the same as the last
<Window.Resources>
<ToolTip x:Key="MyToolTip" Content="{Binding Content}"/>
</Window.Resources>
<TextBlock DataContext="{Binding ElementName=listBox, Path=SelectedItem}" Text="{Binding Content}" ToolTip="{Binding Source={StaticResource MyToolTip}}" />
<TextBlock DataContext="{Binding ElementName=listBox, Path=SelectedItem}" Text="{Binding Content}">
<TextBlock.ToolTip>
<ToolTip Content="{Binding Content}"/>
</TextBlock.ToolTip>
</TextBlock>

Categories