How to add comboboxitem to combobox in style(WPF) - c#

I want to create a combobox style.In the style, I want to add 10 comboboxitems(1, 2,3,...,10) in the combobox.So how can I make it?

Not sure why exactly you would want to do this, but you can of course assign a value to the ItemsSource property in a Style:
xmlns:sys="clr-namespace:System;assembly=mscorlib"
...
<x:Array x:Key="MyComboBoxItems" Type="sys:String">
<sys:String>1</sys:String>
<sys:String>2</sys:String>
<sys:String>3</sys:String>
<sys:String>4</sys:String>
</x:Array>
<Style TargetType="ComboBox">
<Setter Property="ItemsSource" Value="{StaticResource MyComboBoxItems}" />
</Style>

You can do it in XAML and in C#.
In C# for adding items in combox use this code in Loaded event of window:
comboboxname.Items.add("Item1");
comboboxname.Items.add("Item2");
comboboxname.Items.add("Item3");
for show default item use this :
comboboxname.SelectedIndex= number of Item(for example Item1 equals 0);

Related

ItemContainerStyle cleared by loading custom style

So, I have this issue with making a custom treeview with custom treeviewitem:s where the ItemContainerStyle gets cleared by loading the style from the custom style.
It work like this. I have custom MyTreeViewItem based on TreeViewItem.
<TreeViewItem x:Class="UI.MyTreeViewItem"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<TreeViewItem.Resources>
<Style x:Key="MyTreeViewItemStyle" TargetType="TreeViewItem">
<Setter Property="Background" Value="#AEFFC1" />
</Style>
</TreeViewItem.Resources>
</TreeViewItem>
As you can see I have just have a simple coloring here just to make sure that the styling it self works. This how ever wont load unless I do like this in code behind.
EDIT: I know things like coloring don't need to be put here as there was intended to be a template here instead. How ever since noting really worked, I just stripped this down to the bones to make sure I put something super simple in that I know should work in case it was becaouse of the template it self.
public partial class MyTreeViewItem : TreeViewItem
{
public MyTreeViewItem()
{
InitializeComponent();
this.Loaded += MyTreeViewItem_Loaded;
}
private void MyTreeViewItem_Loaded(object sender, RoutedEventArgs e)
{
this.Style = Resources["MyTreeViewItemStyle"] as Style;
}
}
This works grate. Have used this several other times with other controls to have custom styling for controls needed to be loaded up with out having to bother to "restyle" everything over and over again.
How ever there are a issue I come across with this. And that is when ItemContainerStyle is being used of this kind of custom styled controller.
<local:BaseTreeView x:Class="My.Navigator.NavigatorTreeView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:ui="clr-namespace:UI;assembly=BaseCode"
d:DesignHeight="450" d:DesignWidth="800">
<ui:MyTreeView ItemsSource="{Binding Path=Nodes}">
...
<ui:MyTreeView.ItemContainerStyle>
<Style TargetType="{x:Type ui:MyTreeViewItem}">
<Setter Property="FontWeight" Value="Normal" />
<Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}"/>
<Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />
<EventSetter Event="Selected" Handler="TreeView_SelectedItemChanged" />
<EventSetter Event="Expanded" Handler="TreeView_NodeExpanded" />
<EventSetter Event="Collapsed" Handler="TreeView_NodeCollapsed" />
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="FontWeight" Value="Bold" />
</Trigger>
</Style.Triggers>
</Style>
</ui:MyTreeView.ItemContainerStyle>
</ui:MyTreeView>
</local:BaseTreeView>
This ui:MyTreeView.ItemContainerStyle as you see above gets totally ignored once the style is loaded, by this.Style = Resources["MyTreeViewItemStyle"] as Style; in the MyTreeViewItem_Loaded.
That means these Setters, EventSetters and Triggers will not fire at all, as they still are needed to be able to be added as as additional rules.
How can this be solved, so that the predefined styling in the custom control can be loaded and by using this control, you can still can hook up unique rules, like above with out having the the predefined overrule them?
It's not really clear why you are doing what you are doing. All I can say is that you are overwriting the Style value by assigning it explicitly after the control was initialized with the value from the TreeView.ItemContainerStyle.
Normally, on a UserControl, you would set the properties locally on the element:
<TreeViewItem x:Class="UI.MyTreeViewItem"
...
d:DesignHeight="450" d:DesignWidth="800"
Background="#AEFFC1">
</TreeViewItem>
or in code-behind:
private void MyTreeViewItem_Loaded(object sender, RoutedEventArgs e)
{
this.Background =
new SolidColorBrush(ColorConverter.ConvertFromString("#AEFFC1"));
}
When writing a custom Control, you would provide a default Style in Generic.xaml. This is the best solution as it allows the control to be styled (where custom styles are allowed to override default values provided by the default Style). External styles are merged implicitly. You should prefer a custom Control over a UserControl.
Your current code does not allow styling as you forcefully override values provided by a custom Style:
// Overwrite previous property value.
this.Style = someValue;
This is programming 101, first grade: an assignment always overwrites the old value (reference) of the variable.
Assumming that you are knowing what you are doing and you don't want to use one of the above solution, you must manually merge both styles using the Style.BasedOn property:
private void MyTreeViewItem_Loaded(object sender, RoutedEventArgs e)
{
var defaultStyle = Resources["MyTreeViewItemStyle"] as Style;
defaultStyle.BasedOn = this.ItemContainerStyle;
this.Style = defaultStyle;
}
See: Control authoring overview: Models for Control Authoring

How do I make the WPF ComboBox items visible, but non-selectable?

I am trying to make the items of my WPF comboBox visible (preferably greyed out) but not allow the user to select them using c# code.
I have tried the following:
comboBoxName.IsHitTestVisible = false
comboBoxName.Focusable = false
However, this prevents them seeing the contents of the comboBox all together. How would I make the contents visible but cannot be selected in c#?
Set an item container style that will disable each ComboBoxItem.
<ComboBox x:Name="comboBoxName" ItemsSource="{Binding Collection}">
<ComboBox.ItemContainerStyle>
<Style TargetType="{x:Type ComboBoxItem}">
<Setter Property="IsEnabled" Value="False"/>
</Style>
</ComboBox.ItemContainerStyle>
</ComboBox>
If you use code-behind, can define and apply the item container style like this.
var itemContainerStyle = new Style(typeof(ComboBoxItem));
var isEnabledSetter = new Setter(IsEnabledProperty, false);
itemContainerStyle.Setters.Add(isEnabledSetter);
comboBoxName.ItemContainerStyle = itemContainerStyle;

Change FontWeight of specific row of DevExpress GridControl in WPF

I want to Change the FontWeight of a specific row to bold. So i have a DataTable (MyDataTable):
Name Location
-------------------
Mark New-York
Julian Paris
Donald Moscow
which i bind to a DevExpress GridControl
<dxg:GridControl ItemsSource="{Binding MyDataTable}">
Now i would like to Change the FontWeight of the row where the Name is 'Julian'. How can i do this?
I thought using a DataTrigger like:
<dxg:GridControl.Resources>
<Style TargetType="{x:Type dxg:GridRow}">
<Style.Triggers>
<DataTrigger Binding="{Binding MyDataTable.Columns[0]}" Value="Name">
<Setter Property="FontWeight" Value="Bold"/>
</DataTrigger>
</Style.Triggers>
</Style>
</dxg:GridControl.Resources>
but this is not working. I tried several other Options, but did not find a working solution. Can someone please guide me in the right direction? I would very much prefer to do it directly in xaml and not in code behind, if this is possible.
Use FormatConditions Property to format row or cell with condition
<dxg:TableView.FormatConditions> <dxg:FormatCondition Expression="[Name] = 'Julian'" FieldName="Name" />
EDIT:
If you want formatting in code - Formatting in Code

usercontrol (?) for WPF reusable menu

I am a beginner at WPF so please excuse me if this question is too simple :)
I have a listbox which I would like to filter by various filter conditions. This listbox I fill with instances of a particular type. Each filter condition is associated with one of the listbox items' properties. (They are like: this or that string property starts with string XXX.)
For this I would need a menu for each property from which users can select the filter conditions they want to filter the items with. Each property of the same type will have the very same set of menu items with the various filter conditions. (For strings: starts with, ends with... for ints: lower than, higher than, etc.)
The menus require some code behind too so I don't want to program these for each property separately.
My problem is that I don't know in what way could I program these. I cannot program them as UserControls because all what I need is MenuItems in a Menu. But I cannot program them as MenuItem derived classes because I would need the XAML for designing them for each type. Could I create a MenuItem derived class with a XAML somehow? Or do you have any other suggestions?
In WPF, we work with data elements whose public properties are data bound to the properties of various UI controls via DataTemplates. Please see the Data Templating Overview page on MSDN for the full story.
In order to do this, we develop custom classes that contain all of the necessary properties that we need to display and then we declare one or more DataTemplates that define the binding connections between the classes and the UI controls, or MenuItems in your case.
The benefit of this is that in order to display a Menu in the UI, you just need to data bind one of your custom menu class objects to a control in the UI and let the DataTemplate do the rest. So if you want to change the menu contents, you just need to change the data item that is data bound to the Menu.
So to answer your question directly, a Menu control would be most suitable for you to use, but you don't store the Menu properties in your code behind... you store the property values in your custom classes that will be data bound to the Menu control properties:
<Menu ItemsSource="{Binding CollectionOfYourCustomClassItems}" ... />
It is worth pointing out that you may need to set the child MenuItem properties in a Style and not a DataTemplate as usual (taken from the accepted answer to the WPF MenuItem : Mix databound items and static content question (which I recommend that you read) here on Stack Overflow):
<MenuItem Header="_Recent Files" ItemsSource="{Binding Commands,Mode=OneWay}">
<MenuItem.ItemContainerStyle>
<Style TargetType="{x:Type MenuItem}">
<Setter Property="Header" Value="{Binding Path=ShortName}" />
<Setter Property="ToolTip" Value="{Binding Path=FileName}" />
<Setter Property="Command" Value="{Binding Path=OpenCommand}" />
<Setter Property="CommandParameter" Value="{Binding Path=OpenParameter}" />
<Style.Triggers>
<DataTrigger Binding="{Binding Path=IsSeparator}" Value="true">
<Setter Property="MenuItem.Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type MenuItem}">
<Separator Style="{DynamicResource {x:Static MenuItem.SeparatorStyleKey}}"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</MenuItem.ItemContainerStyle>
</MenuItem>
You will find many more tutorials and related questions regarding data binding to MenuItems online, so I won't go over everything again here. Please see the following article to start with:
Binding menus using HeirarchicalDataTemplates

WPF ListView programmatically deselect item

I have used the following approach to bind IsSelected of my items to a Property: WPF ListView Programmatically Select Item
<ListView.ItemContainerStyle>
<Setter Property="IsSelected" Value="{Binding IsSelected}"/>
</ListView.ItemContainerStyle>
Now I am able to select my items in code behind by simple setting the IsSelected property to true. However I am not able to deselect items by setting the IsSelected property of my items to false.
Setting the items property IsSelected to true will trigger the ListViewSelectionChanged event. However setting the property IsSelected of an already selected item to false does not trigger the event. The property will be changed to false but the item remains selected within the ListView. I have also tried using Mode=TwoWay without any success.
I would appreciate any sort of help!
Thank you very much in advance,
Thomas
For OP or others looking to "programmatically" deselect a ListView.
If your ListView rigged up as Single, Extended or Multiple you can always just:
YourlistView.Selecteditem = null;
Or you can use this as well:
YourlistView.UnselectAll();
Looks like you are just missing the TargetType for the style. Add the target type of ListViewItem as per Kent's original code below.
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="IsSelected" Value="{Binding IsGroovy}"/>
</Style>
</ListView.ItemContainerStyle>

Categories