WPF Combox using Itemteplate with multiple sources - c#

I am trying to make WPF Combobox using ItemTemplate. My idea is to create items in combobox like in this tutorial https://www.wpf-tutorial.com/list-controls/combobox-control/, but slightly different. I have 2 Lists, which I want to use as source. A List containing colors for Rectangles = colorList, and a list containing strings for TextBlocks = classesList
List<System.Windows.Media.SolidColorBrush> colorList = new List<System.Windows.Media.SolidColorBrush>
List<string> classesList = new List<string>
<ComboBox Name="cmbClasses" ItemsSource=" ??? " SelectionChanged="cmbClasses_SelectionChanged" Margin="10" >
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Rectangle Name="rectSelectedClassColor" Fill=" ??? " Width="16" Height="16" Margin="0,2,5,2" />
<TextTextBlock Name="cboxSelectedClass" Text=" ??? " MinWidth="50" />
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
Is it possible? How? Thank you.

You should make a new class with a string and Solid color brush as properties
public class NewClass
{
public string Name {get;set;}
public SolidColorBrush Brush {get;set;}
}
Then should make an ObservableCollection of this class and Bind it to your combobox.
ObservableCollection<NewClass> Source = new ObservableCollection<NewClass>();
XAML could look like this.
<ComboBox ItemSource = "{Binding Source}">
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<Rectangle Fill = "{Binding Brush}"/>
<TextBlock Text = "{Binding Name}"/>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>

Related

XAML Get Item text value from ListViewItem

I have a ListView Control witch item is composite by two TextBlocks like that:
<ListView x:Name="resultsList" ItemsSource="{Binding}" HorizontalAlignment="Left" Height="470" Margin="10,0,0,0" VerticalAlignment="Top" Width="342" FontSize="21.333" BorderThickness="0" ItemClick="RedirectPage" IsItemClickEnabled="True" SelectionMode="None">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Margin="0,-4,0,-4">
<StackPanel.Resources>
<Style TargetType="TextBlock">
<Setter Property="Margin" Value="0,0,0,0" />
</Style>
</StackPanel.Resources>
<TextBlock FontSize="35" Text="{Binding target_name}" />
<TextBlock FontSize="15" Text="{Binding type_name}" Opacity="30" Margin="0, 0, 0 ,30"/>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
In the code behind I am trying to get as string the text value from first TextBlock element.
string targetName;
targetName = resultsList.SelectedItem.ToString();
I want that Variable "targetName" то assign the text value ( Text="{Binding target_name}" ) from first TextBlock in the ListView Item.
I will be very thankful if someone is able to help me.
resultsList.SelectedItem should be the object from the collection that is bound to the ListView. So, you can just cast it to the appropriate type and then access the target_name member
Itemssource should be collection. You need to typecast the collection to get the value.
class listData
{
public string target_name { get; set; }
public string type_name{ get; set; }
}
You can get values like this
listData ld= (listData)resultsList.SelectedItem;
string targetName =ld.target_name;

Combo box add item from template

Im trying to add items to the combo box from the code behind to the item template but im getting null. This is what I have so far:
XAML:
<ListBox x:Name="lsbCiertoYFalsoInsideTemplate" Margin="40,0,0,0" ItemTemplate="{StaticResource CiertoYFalsoExcerciseDataTemplate}"/>
App.xaml:
<DataTemplate x:Key="CiertoYFalsoExcerciseDataTemplate">
<Grid>
<StackPanel x:Name="stckCiertoYFalsoInsideTemplate" Margin="0" Orientation="Vertical" Width="1100">
<StackPanel x:Name="stckPreguntasCiertoYFalso" Orientation="Horizontal">
<Grid Height="50" Width="65" DataContext="{Binding CustomValueList}" VerticalAlignment="Top">
<ComboBox x:Name="cbExercises" Style="{StaticResource SA_ComboBoxStyle}" ItemsSource="{Binding CustomOption}" BorderBrush="#CC8C8C8C" VerticalAlignment="Top">
</ComboBox>
</Grid>
<TextBlock HorizontalAlignment="Center" Margin="5,3,0,0" TextWrapping="Wrap" Text="{Binding QuestionNumber}" VerticalAlignment="Top" FontWeight="Bold" Foreground="Black" Width="26" FontFamily="{Binding FontFamily, Source={StaticResource TextBlockStyleManager}}" FontSize="{Binding FontSize, Source={StaticResource TextBlockStyleManager}}"/>
<TextBlock TextWrapping="Wrap" Text="{Binding Question}" Foreground="Black" VerticalAlignment="Top" FontSize="{Binding FontSize, Source={StaticResource TextBlockStyleManager}}" Margin="10,3,0,0" Width="968" FontFamily="{Binding FontFamily, Source={StaticResource TextBlockStyleManager}}"/>
</StackPanel>
</StackPanel>
</Grid>
</DataTemplate>
The error im getting is object out of range.
Code:
private void ComboBoxExercises()
{
ComboBox comboBox = new ComboBox();
ComboboxItem item = new ComboboxItem();
item.Text = "A";
comboBox = (ComboBox)lsbCiertoYFalsoInsideTemplate.FindName("cbExercises");
comboBox.SelectedIndex = 0;
comboBox.Items.Add(item);
}
public class ComboboxItem
{
public string Text { get; set; }
public override string ToString()
{
return Text;
}
}
There's a disconnect in what you're trying to do here. You've specified an ItemTemplate - which defines how each item in the list will look.
But then you're trying to get one single ComboBox back out via the FindName function. Which leads me to believe that you're really intending to set the Template, not the ItemTemplate.
That said, I think the error you're getting is because you're setting the SelectedIndex to 0 when the ComboBox has no items in it. You're telling it to select the first one, but there's nothing to select. You should add the item first, then select it.

Create ItemTemplate for ListBox in code-beind in WPF

I'm trying to create an ItemTemplate for a ListBox programmatically but it doesn't work. I know in XAML I can have something like:
<ListBox x:Name="listbox" BorderThickness="0" Margin="6" Height="400">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Margin="0" Background="Red" Foreground="White" FontSize="18" Text="{Binding}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
But when I'm trying to have the above result programmatically I face a problem which is binding the TextBox.TextProperty:
var textblock = new FrameworkElementFactory(typeof(TextBlock));
// Setting some properties
textblock.SetValue(TextBlock.TextProperty, ??);
var template = new ControlTemplate(typeof(ListBoxItem));
template.VisualTree = textblock;
Please help me on this issue. I couldn't find anything on the web about it.
Thanks in advance.
Try use dot . in Binding, this is the equivalent of {Binding}.
Example:
XAML
<Window x:Class="MyNamespace.MainWindow"
...
Loaded="Window_Loaded">
<ListBox Name="MyListBox" ... />
</Window>
Code-behind
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
var textBlockFactory = new FrameworkElementFactory(typeof(TextBlock));
textBlockFactory.SetValue(TextBlock.TextProperty, new Binding(".")); // Here
textBlockFactory.SetValue(TextBlock.BackgroundProperty, Brushes.Red);
textBlockFactory.SetValue(TextBlock.ForegroundProperty, Brushes.Wheat);
textBlockFactory.SetValue(TextBlock.FontSizeProperty, 18.0);
var template = new DataTemplate();
template.VisualTree = textBlockFactory;
MyListBox.ItemTemplate = template;
}
}
Try this, by binding the "listbox" with ItemsSource and specify the datatemplate below like if you want to bind name then just write {Binding Name}
<ListBox x:Name="listbox" BorderThickness="0" Margin="6" Height="400" ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Margin="0" Background="Red" Foreground="White" FontSize="18" Text="{Binding Name}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

Data binding to Listbox from JSON Response

This is the first time i am doing xaml so please understand that I might be slow in learning
Below is my CS codes. I am trying to bind the "attributes" to listbox.
public DirectionPage()
{
InitializeComponent();
List<Feature> features = App.dResult.directions[0].features;
foreach (Feature f in features)
{
Attributes a = f.attributes;
MessageBox.Show(a.text);
}
}
public ObservableCollection<Feature> test = new ObservableCollection<Feature>();
Below is the XAML codes.
<ListBox x:Name="directionListBox" ItemsSource="{Binding}" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding text}" Style="{StaticResource PhoneTextTitle2Style}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Any help will be greatly appreciated.
I didn't see the collection of attributes.
Possibly what you can do is collect the attributes in a list may be your test and put it in the biding.
Or put the Features collection as itemsource of your list box.
i.e.
public DirectionPage()
{
InitializeComponent();
List<Attributes> LAtributes=new List<Attributes>();
List<Feature> features = App.dResult.directions[0].features;
foreach (Feature f in features)
{
Attributes a=new Attributes();
a = f.attributes;
LAttributes.add(a);
MessageBox.Show(a.text);
}
directionListBox.ItemsSource=Lattribute;
}
and
<ListBox x:Name="directionListBox" ItemsSource="{Binding}" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding Path=text}" Style="{StaticResource PhoneTextTitle2Style}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Hopefully this will help you!

wpf check list box

I m new to wpf.In order to get check list box functionality ,I have added below xaml to my code,but there is no output in my screen.only blank,what it could be?
<TabItem Header="Samples" >
<ListBox Margin="10" Width="373" Height="236">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="MyText"/>
<CheckBox IsChecked="False"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</TabItem>
just have a look at this basic sample
http://merill.net/2009/10/wpf-checked-listbox/
List box is a bit wired for such task..Have a look at ItemsControl.
Here is the code i use:
<ItemsControl
ItemsSource="{Binding ***}" IsTabStop="False">
<ItemsControl.ItemTemplate>
<DataTemplate>
<CheckBox
Content="{Binding Name}"
IsChecked="{Binding IsSelected}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
Replace your code with this
<TabItem Header="Roles" >
<ListBox Margin="10" Width="373" Height="236">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="MyText"/>
<CheckBox IsChecked="False"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBoxItem>Hi</ListBoxItem>
</ListBox>
</TabItem>
and tell us if it still shows blank
Better still, just use the new CheckListBox control in the Extended WPF Toolkit
http://wpftoolkit.codeplex.com/wikipage?title=CheckListBox&referringTitle=Home
This might help
1.Inorder to work datatemplate you must specify itemsource, here i have bounded a Stateslist a collection of items into it.
2.Also set the Datacontext to ViewModel or the CodeBehind as datacontext.
3.Datacontext will distribute the StateList properties collection to the listbox itemsource
using codebehind -
public Window1()
{
InitializeComponent();
this.DataContext = this;
LoadData();
}
using viewmodel
public Window1()
{
InitializeComponent();
DataContext = new Window1ViewModel();
LoadData();
}
//MyItemsource Property for listbox
private ObservableCollection<States> _stateslist;
public ObservableCollection<States> StatesList
{
get { return _stateslist; }
set
{
_stateslist = value;
RaisePropertyChanged(() => StatesList);
}
}
// Sample Data Loading
public void LoadData()
{
StatesList = new ObservableCollection<States>();
StatesList.Add(new States
{
StateName = "Kerala"
});
StatesList.Add(new States
{
StateName = "Karnataka"
});
StatesList.Add(new States
{
StateName = "Goa"
});
}
Window1.Xaml
<ListBox ItemsSource="{Binding StatesList}" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<CheckBox IsChecked="{Binding IsSelected"} Content="{Binding StateName}" />
<TextBox Text="{Binding TextBoxValue}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Check this out it isworking..you are using TabItem but you didnt define it in TabControl
<TabControl>
<TabItem Header="Tab1">
<ListBox Margin="10" Width="373" Height="236">
<ListBox.Items>
<StackPanel Orientation="Horizontal">
<TextBlock Text="MyText"/>
<CheckBox IsChecked="False"/>
</StackPanel>
</ListBox.Items>
</ListBox>
</TabItem>
</TabControl>
If you are new in WPF use XamlPadX it will give you great help to practice out on it..

Categories