Dynamically Create TextBlock and TextBox in XAML WPF - c#

My Question Is I have a grid where number of TextBlock and TextBox will vary as per the ComboBox SelectedItem Change
So, what I want is that I have written a function for get the details of the TextBlock and TextBox.
C# Function
public void GetAdditionalAttributes()
{
using (Entities _entities = new Entities())
{
var attributeAll = (from c in _entities.AdditionalAttributeValues
where c.DeviceID == 35
select new AttributesClass { AttributeValue = c.AdditionalAttributeValue1, AttributeName = c.AdditionalAttribute.Name }).ToList();
DeviceAttributes = new ObservableCollection<AttributesClass>(attributeAll);
}
}
Now In the XAML I was trying:
<Style x:Key="AdditionalAttributeDisplay"
TargetType="Grid"
x:Name="AdditionalAttributeDisplay"
>
<Style.Resources>
<Style TargetType="ItemsControl">
<Setter Property="ItemsSource"
Value="{Binding DeviceAttributes}" />
<Style.Triggers>
<DataTrigger Binding="{Binding SelectedValue, ElementName=DeviceTypeComboBox}"
Value="1">
<Setter Property="ItemsSource"
Value="{Binding DeviceAttributes}" />
</DataTrigger>
</Style.Triggers>
</Style>
</Style.Resources>
</Style>
But I don't know how to create a TextBlock or TextBox with ItemSource binding.

You can change the ItemTemplate of your ItemsControl.
<Style TargetType="ItemsControl">
<Setter Property="ItemTemplate">
<Setter.Value>
<ItemContainerTemplate>
<Grid>
<TextBox Width="100" Height="20" Text={Binding AttributeName}/>
</Grid>
</ItemContainerTemplate>
</Setter.Value>
</Setter>
</Style>
In above snippet replace PropertyName with DeviceAttributes member you want

Related

WPF Combobox binding issue with object

I have found several example of wpf combobox binding but when trying to adapt it I don't get the expected results. What appears in the combobox instead of the value is this:
CuttingProblemHelper.Models.ComboBoxPairs
Can please anyone help?
Example of data in the SQL table:
Id CutProbCategId Problem
1 1 Brins coupés
2 1 Brins grafignés
3 1 Fil non dégainé
What I try to acheive is having a key, value pair for each entry in the combobox from an sql table.
So I created a class to store key, value pair:
namespace CuttingProblemHelper.Models {
public class ComboBoxPairs
{
public int _Key { get; set; }
public string _Value { get; set; }
public ComboBoxPairs(int _key, string _value)
{
_Key = _key;
_Value = _value;
}
} }
Next get the data from the table and add them to the object ComboBoxPairs
private void AddProblemCategtoCombobox(int categ)
{
// erase list
cmbxProblem.ItemsSource = null;
// get list
DataRow[] CutProblemsRows = gediDataSet.CutProblems.Select("CutProbCategId= " + categ);
// we have rows
if (CutProblemsRows != null)
{
// initialize object ComboBoxPairs
List<ComboBoxPairs> cbp = new List<ComboBoxPairs>();
foreach (DataRow row in CutProblemsRows)
{
// add id and problem key, value pair
cbp.Add(new ComboBoxPairs(int.Parse(row["Id"].ToString()), row["Problem"].ToString()));
}
// define properties of combobox
cmbxProblem.DisplayMemberPath = "_Value";
cmbxProblem.SelectedValuePath = "_Key";
// bind comboboxpairs list
cmbxProblem.ItemsSource = cbp.ToList();
}
}
Here's the XAML of the combobox and formatting of the display of items:
<ComboBox x:Name="cmbxProblem" Grid.Column="1" Margin="10,10,10,10" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" SelectionChanged="cmbxProblem_SelectionChanged" FontSize="40" ItemsSource="{Binding Collection}" Grid.ColumnSpan="2">
<ComboBox.ItemContainerStyle>
<Style TargetType="{x:Type ComboBoxItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ComboBoxItem}">
<Label Name="lbl" Content="{Binding}" ></Label>
<ControlTemplate.Triggers>
<Trigger Property="IsHighlighted" Value="True">
<Setter TargetName="lbl" Property="FontStyle" Value="Normal"></Setter>
<Setter TargetName="lbl" Property="Background" Value="AliceBlue"></Setter>
</Trigger>
<Trigger Property="IsSelected" Value="True">
<Setter TargetName="lbl" Property="FontStyle" Value="Italic"></Setter>
</Trigger>
<Trigger Property="IsSelected" Value="False">
<Setter TargetName="lbl" Property="FontStyle" Value="Normal"></Setter>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ComboBox.ItemContainerStyle>
</ComboBox>
Thank you very much!
I found a solution but the combobox does not only display the value but it displays the paired key and value. But when a value is selected it displays only the selected value. Anyone knows what to change to show only the value without the key?
See pictures to better understand.
Here's the solution I came up with after searching several combobox solutions:
In the XAML
<ComboBox x:Name="cmbxProblem" Grid.Column="1" Margin="10,10,10,10" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" SelectionChanged="cmbxProblem_SelectionChanged" FontSize="40" ItemsSource="{Binding MyCollection}" DisplayMemberPath="_Value" SelectedValuePath="_Key" Grid.ColumnSpan="2">
<ComboBox.ItemContainerStyle>
<Style TargetType="{x:Type ComboBoxItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ComboBoxItem}">
<Label Name="lbl" Content="{Binding}" ></Label>
<ControlTemplate.Triggers>
<Trigger Property="IsHighlighted" Value="True">
<Setter TargetName="lbl" Property="FontStyle" Value="Normal"></Setter>
<Setter TargetName="lbl" Property="Background" Value="AliceBlue"></Setter>
</Trigger>
<Trigger Property="IsSelected" Value="True">
<Setter TargetName="lbl" Property="FontStyle" Value="Italic"></Setter>
</Trigger>
<Trigger Property="IsSelected" Value="False">
<Setter TargetName="lbl" Property="FontStyle" Value="Normal"></Setter>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ComboBox.ItemContainerStyle>
</ComboBox>
In the code behind:
private void AddProblemCategtoCombobox(int categ)
{
// delete list
cmbxProblem.ItemsSource = null;
// get items for list
DataRow[] CutProblemsRows = gediDataSet.CutProblems.Select("CutProbCategId= " + categ);
// we have items
if (CutProblemsRows != null)
{
// create collection
MyCollection = new ObservableCollection<KeyValuePair<int, string>>();
foreach (DataRow row in CutProblemsRows)
{
// fill collection with items
MyCollection.Add(new KeyValuePair<int, string>(int.Parse(row["Id"].ToString()), row["Problem"].ToString()));
}
// define properties for the combobox
cmbxProblem.DisplayMemberPath = "Value";
cmbxProblem.SelectedValuePath = "Key";
cmbxProblem.ItemsSource = MyCollection;
}
}

WPF: Change the CornerRadius for only the last item in a ListBox

I've created a ListBox with round corners. I've also added a bottom border to all ListBoxItems except for the last one.
The ListBoxItems, however, have normal, square corners, so when hovering over or selecting the first or last items, you can see an overlap between the round ListBox corner and the square ListBoxItem corners.
I can't set CornerRadius the same way I set BorderThickness - I think that's because CornerRadius is a property of the Border property(?).
I can force ALL ListBoxItems to have all round corners which fixes the overlap, but then ALL ListBoxItems have round underlines & selections- which I'd rather not have. I only want those round corners on the bottom of the last item (and eventually top of the first item)
I would like to use a similar sort of trigger for setting CornerRadius that I do for setting BrushThickness.
Is there a way to set the corner radius of just the last item in a ListBox? (and eventually the first item)
In my test, I'm using the MaterialDesignTheme package from NuGet. Because that's non-standard, I'll add all my code here (also note: I'm new to WPF, so feel free to critique anything that looks off):
App.xaml:
<Application . . .
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<materialDesign:BundledTheme BaseTheme="Light" PrimaryColor="DeepPurple" SecondaryColor="Lime" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Defaults.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>
MainWindow.xaml: (Note, if you uncomment the commented section, it styles all ListBoxItems like I would want only the last ListBoxItem styled)
<Window . . .
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
TextElement.Foreground="{DynamicResource MaterialDesignBody}"
TextElement.FontWeight="Regular"
TextElement.FontSize="13"
TextOptions.TextFormattingMode="Ideal"
TextOptions.TextRenderingMode="Auto"
Background="{DynamicResource MaterialDesignPaper}"
FontFamily="{DynamicResource MaterialDesignFont}">
<Window.Resources>
<local:IsLastItemInContainerConverter x:Key="IsLastItemInContainerConverter" />
</Window.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="200"/>
<ColumnDefinition Width="200*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="40"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<StackPanel Grid.Row="1" Margin="5">
<ListBox x:Name="GameListBox"
BorderBrush="{DynamicResource MaterialDesignDivider}"
BorderThickness="1">
<ListBox.Resources>
<Style TargetType="Border">
<Setter Property="CornerRadius" Value="10"/>
</Style>
</ListBox.Resources>
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem" BasedOn="{StaticResource MaterialDesignListBoxItem}">
<!--<Style.Resources>
<Style TargetType="Border">
<Setter Property="CornerRadius" Value="0 0 10 10"/>
</Style>
</Style.Resources>-->
<Style.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource Self},
Converter={StaticResource IsLastItemInContainerConverter}}" Value="False">
<Setter Property="BorderThickness" Value="0 0 0 1" />
<Setter Property="BorderBrush" Value="{DynamicResource MaterialDesignDivider}"/>
</DataTrigger>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource Self},
Converter={StaticResource IsLastItemInContainerConverter}}" Value="True">
<Setter Property="BorderThickness" Value="0" />
<Setter Property="BorderBrush" Value="Transparent"/>
</DataTrigger>
</Style.Triggers>
</Style>
</ListBox.ItemContainerStyle>
<ListBoxItem>
<TextBlock> Plain
</TextBlock>
</ListBoxItem>
<ListBoxItem>
<TextBlock> Old
</TextBlock>
</ListBoxItem>
<ListBoxItem>
<TextBlock> ListBox
</TextBlock>
</ListBoxItem>
<ListBoxItem>
<TextBlock> Full of junk
</TextBlock>
</ListBoxItem>
</ListBox>
</StackPanel>
</Grid>
</Window>
...and in MainWindow.xaml.cs, I have defined the converter to find the last item:
public class IsLastItemInContainerConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
DependencyObject item = (DependencyObject)value;
ItemsControl ic = ItemsControl.ItemsControlFromItemContainer(item);
return ic.ItemContainerGenerator.IndexFromContainer(item)
== ic.Items.Count - 1;
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
First of all, please understand that the MaterialDesignTheme package was not used in my code.
Items.cs
Instead of using Converter, I added a model class.
public class Items
{
public string Name { get; set; }
public bool IsFirst { get; set; }
public bool IsLast { get; set; }
}
App.xaml
I defined styles of ListBoxItem, ListBox like below.
<Style TargetType="{x:Type ListBoxItem}" x:Key="listboxitem">
<Setter Property="FocusVisualStyle" Value="{x:Null}"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<Border x:Name="border"
Background="White"
BorderBrush="#AAAAAA"
BorderThickness="1 1 1 0"
CornerRadius="0">
<TextBlock Text="{Binding Name}" Foreground="Black" FontSize="13" FontWeight="Normal"
Margin="10" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Border>
<ControlTemplate.Triggers>
<DataTrigger Binding="{Binding IsFirst}" Value="True">
<Setter TargetName="border" Property="CornerRadius" Value="10 10 0 0"/>
</DataTrigger>
<DataTrigger Binding="{Binding IsLast}" Value="True">
<Setter TargetName="border" Property="CornerRadius" Value="0 0 10 10"/>
<Setter TargetName="border" Property="BorderThickness" Value="1 1 1 1"/>
</DataTrigger>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="border" Property="Background" Value="#666666"/>
</Trigger>
<Trigger Property="IsSelected" Value="True">
<Setter TargetName="border" Property="Background" Value="#666666"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style TargetType="{x:Type ListBox}" x:Key="listbox">
<Setter Property="Width" Value="200"/>
<Setter Property="Height" Value="200"/>
<Setter Property="ItemContainerStyle" Value="{StaticResource listboxitem}"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBox}">
<Border Background="Transparent"
BorderBrush="#AAAAAA"
BorderThickness="0 0 0 0"
CornerRadius="10">
<ItemsPresenter/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<StackPanel/>
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
</Style>
MainWindow.xaml
<ListBox x:Name="lbx" Style="{StaticResource listbox}"/>
MainWindow.xaml.cs
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
lbx.ItemsSource = GetItems();
}
private List<Items> GetItems()
{
List<Items> source = new List<Items>();
source.Add(new Items { Name = "Plain", IsFirst = true });
source.Add(new Items { Name = "Old" });
source.Add(new Items { Name = "ListBox" });
source.Add(new Items { Name = "Full of junk", IsLast = true }); ;
return source;
}
}
It will be shown like this..

Editable DatagridComboBoxColumn in WPF using C#

I'm using WPF DataGrid control with dynamic columns binding at run time.(DataGrid columns are dynamic)
Sample code is as below
.xaml is having below code
<Style TargetType="ComboBox" x:Key="ComboBoxEditingStyle">
<Setter Property="ItemsSource" Value="{Binding Path=DefinedFormatters}" />
<Setter Property="IsDropDownOpen" Value="False" />
<Setter Property="IsEditable" Value="True" />
<Setter Property="SelectedValue" Value="Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
<Setter Property="ItemTemplate">
<Setter.Value>
<DataTemplate>
<TextBlock Text="{Binding Path=Name}"></TextBlock>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
.xaml.cs file is having below code,
Binding theBinding = new Binding();
theBinding.Mode = BindingMode.TwoWay;
theBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
theBinding.ValidatesOnDataErrors = true;
DataGridComboBoxColumn colSuggestionList = new DataGridComboBoxColumn();
// theCollection is Collection<string>
colSuggestionList.ItemsSource = theCollection;
colSuggestionList.SelectedValueBinding = theBinding;
colSuggestionList.Visibility = Visibility.Visible;
colSuggestionList.EditingElementStyle = dgMainTemplate.FindResource("ComboBoxEditingStyle") as Style;
// dgMainTemplate is wpf DataGrid
dgMainTemplate.Columns.Add(colSuggestionList);
Column added properly, but I want to make this column as editable. User should be able to select either existing item from available list or enter a new value which is not exists in available list.
Here EditingElementStyle will add editable combobox but items are not showing in combobox until user selects any item.
Finally I got solution to this problem, Modified code is as below,
<Style x:Key="TextBlockComboBoxStyle" TargetType="{x:Type ComboBox}" BasedOn="{StaticResource {x:Type ComboBox}}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ComboBox}">
<Label Content="{TemplateBinding Text}" Style="{StaticResource {x:Type Label}}" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style TargetType="ComboBox" x:Key="ComboBoxEditingStyle">
<Setter Property="ItemsSource" Value="{Binding Path=DefinedFormatters}" />
<Setter Property="IsDropDownOpen" Value="False" />
<Setter Property="IsEditable" Value="True" />
</Style>
.cs code is,
Binding theBinding = new Binding();
theBinding.Mode = BindingMode.TwoWay;
theBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
theBinding.ValidatesOnDataErrors = true;
DataGridComboBoxColumn colSuggestionList = new DataGridComboBoxColumn();
// theCollection is Collection<string>
colSuggestionList.ItemsSource = theCollection;
colSuggestionList.SelectedValueBinding = theBinding;
colSuggestionList.Visibility = Visibility.Visible;
colSuggestionList.EditingElementStyle = dgMainTemplate.FindResource("ComboBoxEditingStyle") as Style;
colSuggestionList.EditingElementStyle = dgMainTemplate.FindResource("ComboBoxEditingStyle") as Style;
colSuggestionList.ElementStyle = dgMainTemplate.FindResource("TextBlockComboBoxStyle") as Style;
// dgMainTemplate is wpf DataGrid
dgMainTemplate.Columns.Add(colSuggestionList);

wpf Listview with textbox error

I got a listview with a gridview cell template, as a textbox.
I can change the itemssource in the ui at runtime, but I can't do it, in code behind..
Please any ideas why would be a appreciated.
it's bound to a custom list.
this is my code so far:
Xaml template.
<Style TargetType="{x:Type TextBlock}" x:Key="GridBlockStyle">
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="Visibility" Value="{Binding Path=IsSelected, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListViewItem}}, Converter={StaticResource boolToVis}, ConverterParameter=False}" />
</Style>
<Style TargetType="{x:Type FrameworkElement}" x:Key="GridEditStyle">
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="Visibility" Value="{Binding Path=IsSelected, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListViewItem}}, Converter={StaticResource boolToVis}, ConverterParameter=True}" />
</Style>
<DataTemplate x:Key="txt_Field" DataType="{x:Type GridViewColumn}">
<Grid>
<TextBlock Text="{Binding Path=txt}" Style="{StaticResource GridBlockStyle}"/>
<TextBox Style="{StaticResource GridEditStyle}" Text="{Binding Path=txt}"/>
</Grid>
</DataTemplate>
Code behind:
DataTemplate t_txt = (DataTemplate)window.FindResource("txt_Field");
gridView.Columns.Add(new GridViewColumn { Header = "txt", CellTemplate = t_txt });
it updates the itemssource and as soon as the foreach loops are done the Entries are being overriden to null.
try
{
foreach (Items1 item in TempList)
{
foreach (Items1 item2 in list)
{
if (item.num == item2.num)
{
item2.txt = item.txt;
}
}
}
listview.Items.Refresh();
}
catch { }
I found a solution, but I still want to know why it happent..
this is the solution:
for (int i = 0; i < TempList.Count; i++)
{
if (Order_TempList[i].txt == ((Items1)listview.SelectedItem).txt)
{
((Items1)listview.SelectedItem).txt = Order_TempList[i].txt;
i = TempList.Count;
}
}
I can see the error very clearly now.
It's because there is two lists and the visual list (listview.Items) is being updated and not the physical list (TempList).

Cannot change the style of the selected item in a ListBox

I´m trying to change the focused/selected item of a ListBox. My application is based on this article.
At the moment I´m trying to set the ListBoxItem style via data templates:
<DataTemplate x:Key="ItemTemplate">
<TextBlock Text="{Binding}"
Foreground="Black"
FontFamily="Segoe UI"
FontSize="22"
HorizontalAlignment="Left"
Padding="15,10,0,0"
/>
</DataTemplate>
<DataTemplate x:Key="SelectedTemplate">
<TextBlock Text="{Binding}"
Foreground="Red"
FontFamily="Segoe UI"
FontSize="30"
HorizontalAlignment="Left"
Padding="15,10,0,0"
/>
</DataTemplate>
My idea was to switch between those templates using a trigger:
<Style TargetType="{x:Type ListBoxItem}" x:Key="ContainerStyle">
<Setter Property="ContentTemplate" Value="{StaticResource ItemTemplate}" />
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="ContentTemplate" Value="{StaticResource SelectedTemplate}" />
</Trigger>
</Style.Triggers>
</Style>
The ListBox looks like this:
<ListBox x:Name="valuesItemsCtrl"
BorderThickness="0"
ItemContainerStyle="{StaticResource ContainerStyle}"
Background="Transparent"
Tag="{Binding }">
<ListBox.AlternationCount>
<Binding>
<Binding.Path>Values.Count</Binding.Path>
</Binding>
</ListBox.AlternationCount>
<ListBox.ItemsSource>
<Binding>
<Binding.Path>Values</Binding.Path>
</Binding>
</ListBox.ItemsSource>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
At the end I add the template to another ListBox:
<ListBox x:Name="tumblersCtrl"
BorderThickness="0"
Background="Transparent"
ItemsSource="{Binding Tumblers, ElementName=thisCtrl}"
ItemTemplate="{StaticResource TumblerTemplate}">
</ListBox>
Thanks for any help or hint!
Use ItemTemplate and data triggers:
<ListBox ItemsSource="{Binding}">
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="IsSelected" Value="{Binding IsSelected}"/>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"
Foreground="Black"
FontFamily="Segoe UI"
FontSize="22"
HorizontalAlignment="Left"
Padding="15,10,0,0"
x:Name="tbName"/>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding IsSelected}" Value="True">
<Setter TargetName="tbName" Property="Foreground" Value="Red"/>
<Setter TargetName="tbName" Property="FontSize" Value="30"/>
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
where bound data is a collection of:
public class ViewModel : ViewModelBase
{
public String Name
{
get { return name; }
set
{
if (name != value)
{
name = value;
OnPropertyChanged("Name");
}
}
}
private String name;
public Boolean IsSelected
{
get { return isSelected; }
set
{
if (isSelected != value)
{
isSelected = value;
OnPropertyChanged("IsSelected");
}
}
}
private Boolean isSelected;
}
Window code-behind:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new[]
{
new ViewModel { Name = "John", IsSelected = true },
new ViewModel { Name = "Mary" },
new ViewModel { Name = "Pater" },
new ViewModel { Name = "Jane" },
new ViewModel { Name = "James" },
};
}
}
If you want to change the templates use DataTemplateSelector.
Dismiss your ContainerStyle and instead set the ListBox.ItemsTemplateSelector to your custom datatemplateselector as static resource.
You can find a detailed example in this link.
EDIT :
According to your comment you don't need DataTemplate just set these two properties in the Trigger:
<Style TargetType="{x:Type ListBoxItem}" x:Key="ContainerStyle">
<Setter Property="Foreground" Value="Black" />
<Setter Property="FontSize" Value="22" />
<Setter Property="FontFamily" Value="Segoe UI" />
<Setter Property="HorizontalAlignment" Value="Left" />
<Setter Property="Padding" Value="15,10,0,0" />
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Foreground" Value="Red" />
<Setter Property="FontSize" Value="30" />
</Trigger>
</Style.Triggers>
</Style>

Categories