How to bind a ComboBox to generic dictionary with xaml code - wpf

I'm using the following code :
private Dictionary<string, string> GetNumber { get; set; }
public ReportsLetterTra()
{
GetNumber = new Dictionary<string, string>
{
{"1", "First"},
{"2", "Second"}
};
InitializeComponent();
}
xaml code :
<ComboBox
DisplayMemberPath="value"
SelectedValuePath="key"
ItemsSource="{Binding ElementName=reportslettra,Path=GetNumber}"
SelectedIndex="0" Name="cmbFromNumber" />
Why is not bind GetNumber to cmbFromNumber?!
Update :
my complete code in behind file :
using System.Collections.Generic;
using System.Windows;
namespace WpfApplication20
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public Dictionary<string, string> GetNumber { get; set; }
public Window1()
{
GetNumber = new Dictionary<string, string>
{
{"1", "First"},
{"2", "Second"}
};
InitializeComponent();
}
}
}
my complete xaml code:
<Window x:Class="WpfApplication20.Window1" Name="eportslettra"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid Height="26">
<ComboBox DisplayMemberPath="Value" SelectedValuePath="Key"
ItemsSource="{Binding ElementName=reportslettra,Path=GetNumber}"
SelectedIndex="0" Name="cmbFromNumber" />
</Grid>
</Window>
Where is my wrong?
Why is not bind GetNumber to cmbFromNumber?!

Your property is marked as private, make it public. Also, correct the casing on your ComboBox to Value and Key. Thirdly, your binding expression looks invalid, double check this. Finally, it looks like your properties are part of the view's code behind file. You might consider the MVVM design pattern.
Update
Your Window has the Name of 'eportslettra', but your binding expression uses the ElementName 'reportslettra'. Correct one of them.

Related

WPF DataGrid not loading data

I am a beginner in C# and WPF .
I have created a user control LogTable.atxml which contains a DataGrid and added it to the MainWindow.xaml .
The Table is displayed but the contents are not being fetched.
I think the issue is im not able to sent the Itemsource in the right way.
[Result]Please help.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TableTest.UserControls
{
class Tabledata
{
string A{ get; set; }
string B { get; set; }
string C { get; set; }
public Tabledata(string a, string b, string c)
{
A = a;
B = b;
C =c;
}
}
}
namespace TableTest.UserControls
{
/// <summary>
/// Interaction logic for LogTable.xaml
/// </summary>
public partial class LogTable : UserControl
{
ObservableCollection<Tabledata> list;
public LogTable()
{
InitializeComponent();
list = getTableDetails();
this.logGrid.ItemsSource = list;
}
private ObservableCollection<Tabledata> getTableDetails()
{
ObservableCollection<Tabledata> list= new ObservableCollection<Tabledata>();
Tabledata data = new Tabledata("aaa", "aaa", "aaa");
Tabledata data1 = new Tabledata("bbb", "aaa", "aaa");
Tabledata data2 = new Tabledata("ccc", "aaa", "aaa");
list.Add(data);
list.Add(data1);
list.Add(data2);
return list;
}
}
}
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
}
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:UserControls="clr-namespace:TableTest.UserControls" x:Class="TableTest.MainWindow"
Title="MainWindow" Height="350" Width="525">
<Grid>
<UserControls:LogTable x:Name="logtable" HorizontalAlignment="Left" Margin="0,209,0,0" VerticalAlignment="Top" Width="287" Height="111"/>
</Grid>
</Window>
<UserControl x:Class="TableTest.UserControls.LogTable"
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"
>
<DataGrid x:Name="logGrid" AutoGenerateColumns="False"
Height="290"
HorizontalAlignment="Left"
VerticalAlignment="Top" Width="290"
ItemsSource="{Binding list}"
>
<DataGrid.Columns >
<DataGridTextColumn Binding="{Binding Path=A}" MinWidth="50" Header="Column 1"/>
<DataGridTextColumn Binding="{Binding Path=B}" MinWidth="50" Header="Column 2"/>
<DataGridTextColumn Binding="{Binding Path=C}" MinWidth="50" Header="Column 3"/>
</DataGrid.Columns>
</DataGrid>
</UserControl>
I think you need to do a few things
1. Your ItemSource needs to bind to a property. So your code should look something like
public partial class LogTable : UserControl
{
public ObservableCollection<Tabledata> list {get;set;}
public LogTable()
{
InitializeComponent();
DataContext=this;
list = new ObservableCollection<TableData>();
list = getTableDetails();
this.logGrid.ItemsSource = list;
}
You need to set your data context of your user control. If you are just using the codebehind you can get away with setting the DataContext in your usercontrols constructor like in the code above. But probably in the future you are going to want to use the mvvm pattern and set your datacontext to your viewmodel.
Note: You will need to set your datacontext of the mainwindow if you want to access any information from that window's codebehind (or whatever you want to bind data from).
Here is a good resource to read up on mvvm.
Update: Just saw your xaml. Since you named the Datagrid you can actually get away with not setting the DataContext as your as setting the ItemSource directly in your code. However, since you don't have your datacontext set you can remove the ItemSource={Binding list} from your xaml. That will only work if you have the list property available on your DataContext.
Update 2: You also need to make your properties public on your TableData class. then it will work
class Tabledata
{
public string A { get; set; }
public string B { get; set; }
public string C { get; set; }
public Tabledata(string a, string b, string c)
{
A = a;
B = b;
C = c;
}
}

How to use Message.Attach to call methods inside another object

I have a view model which has another class set as its property. The another class contains implementations of ICommand as its properties. I would like to execute one of the commands on a double click.
Unfortunatelly, Caliburn.Micro raises an exception instead ("No target found for method Commands.Command.Execute.").
I've tried to search the net and read the documentation, but without any success.
How to do it correctly?
Note: In real application, the message might be attached to a grid view which might have a different DataContext than the view model containing the commands class.
The XAML:
<Window x:Class="WpfApplication8.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:cal="http://www.caliburnproject.org">
<Grid>
<TextBox
cal:Message.Attach="[Event MouseDoubleClick]
= [Action Commands.Command.Execute(null)]" />
</Grid>
</Window>
The code-behind class:
namespace WpfApplication8
{
public partial class MainWindow
{
public Commands Commands { get; set; }
public MainWindow()
{
this.Commands =
new Commands { Command = new Command { MainWindow = this } };
this.InitializeComponent();
this.DataContext = this;
}
}
public class Commands
{
public Command Command { get; set; }
}
public class Command
{
public MainWindow MainWindow { get; set; }
public void Execute(object parameter)
{
this.MainWindow.Title = "Executed";
}
}
}
As #alik commented, complete solution is:
<Window x:Class="WpfApplication8.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:cal="http://www.caliburnproject.org">
<Grid>
<TextBox
cal:Message.Attach="[Event MouseDoubleClick] = [Action Execute(null)]"
cal:Action.TargetWithoutContext="{Binding Commands.Command}"/>
</Grid>
</Window>

Binding to a property of of the SelectedItem Property

I am currently experimenting with WPF.
One thing, I wanted to do was a master to detail selection over multiple comboboxes.
I have a ViewModel with GroupItems that i use as ItemSource for the first combobox. These GroupItems have a Property called Childs, which includes a List of items that belong to this group.
I can't find a way to bind the comboBox1.SelectedItem.Childs as Itemsource for the second comboBox.
Right now I only got to
ItemsSource="{Binding ElementName=comboBox1, Path=SelectedItem}"
But I don't get the Property of the SelectedItem. How can this be done? Or is this not the WPF way to this?
Is there any good website to learn how to select different elements? Eplaining Path, XPath, Source and everything?
Thanks for any help.
Your binding above isn't attempting to bind to Childs, only SelectedItem.
Try something like this:
Window1.xaml
<Window x:Class="WpfApplication5.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<StackPanel>
<ComboBox x:Name="_groups" ItemsSource="{Binding Groups}" DisplayMemberPath="Name"/>
<ComboBox ItemsSource="{Binding SelectedItem.Items, ElementName=_groups}"/>
</StackPanel>
</Window>
Window1.xaml.cs
using System.Windows;
namespace WpfApplication5 {
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window {
public MainWindow() {
InitializeComponent();
var model = new ViewModel();
var g1 = new Group { Name = "Group1" };
g1._items.Add("G1C1");
g1._items.Add("G1C2");
g1._items.Add("G1C3");
model._groups.Add(g1);
var g2 = new Group { Name = "Group2" };
g2._items.Add("G2C1");
g2._items.Add("G2C2");
g2._items.Add("G2C3");
model._groups.Add(g2);
var g3 = new Group { Name = "Group3" };
g3._items.Add("G3C1");
g3._items.Add("G3C2");
g3._items.Add("G3C3");
model._groups.Add(g3);
DataContext = model;
}
}
}
ViewModel.cs
using System;
using System.Collections.Generic;
namespace WpfApplication5
{
public class Group {
internal List<String> _items = new List<string>();
public IEnumerable<String> Items {
get { return _items; }
}
public String Name { get; set; }
}
public class ViewModel
{
internal List<Group> _groups = new List<Group>();
public IEnumerable<Group> Groups
{
get { return _groups; }
}
}
}

Sorting a combobox purely in XAML

I'm surprised that no one has asked this before here... well, at least I haven't found an answer here or anywhere else, actually.
I have a ComboBox that is databound to an ObservableCollection. Everything worked great until the guys wanted the contents sorted. No problem -- I end up changing the simple property out:
public ObservableCollection<string> CandyNames { get; set; } // instantiated in constructor
for something like this:
private ObservableCollection<string> _candy_names; // instantiated in constructor
public ObservableCollection<string> CandyNames
{
get {
_candy_names = new ObservableCollection<string>(_candy_names.OrderBy( i => i));
return _candy_names;
}
set {
_candy_names = value;
}
}
This post is really two questions in one:
How can I sort a simple ComboBox of strings in XAML only. I have researched this and can only find info about a SortDescription class, and this is the closest implementation I could find, but it wasn't for a ComboBox.
Once I implemented the sorting in code-behind, it my databinding was broken; when I added new items to the ObservableCollection, the ComboBox items didn't update! I don't see how that happened, because I didn't assign a name to my ComboBox and manipulate it directly, which is what typically breaks the binding.
Thanks for your help!
You can use a CollectionViewSource to do the sorting in XAML, however you need to refresh it's view if the underlying collection changes.
XAML:
<Window x:Class="CBSortTest.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase"
Height="300" Width="300">
<Window.Resources>
<CollectionViewSource Source="{Binding Path=CandyNames}" x:Key="cvs">
<CollectionViewSource.SortDescriptions>
<scm:SortDescription />
</CollectionViewSource.SortDescriptions>
</CollectionViewSource>
</Window.Resources>
<StackPanel>
<ComboBox ItemsSource="{Binding Source={StaticResource cvs}}" />
<Button Content="Add" Click="OnAdd" />
</StackPanel>
</Window>
Code behind:
using System;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Data;
namespace CBSortTest
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
CandyNames = new ObservableCollection<string>();
OnAdd(this, null);
OnAdd(this, null);
OnAdd(this, null);
OnAdd(this, null);
DataContext = this;
CandyNames.CollectionChanged +=
(sender, e) =>
{
CollectionViewSource viewSource =
FindResource("cvs") as CollectionViewSource;
viewSource.View.Refresh();
};
}
public ObservableCollection<string> CandyNames { get; set; }
private void OnAdd(object sender, RoutedEventArgs e)
{
CandyNames.Add("Candy " + _random.Next(100));
}
private Random _random = new Random();
}
}

How to force ListBox to reload properties of ListBoxItems

Is there any way, how to force ObservableCollection to fire CollectionChanged?
I have a ObservableCollection of objects ListBox item source, so every time I add/remove item to collection, ListBox changes accordingly, but when I change properties of some objects in collection, ListBox still renders the old values.
Even if I do modify some properties and then add/remove object to the collection, nothing happens, I still see old values.
Is there any other way around to do this? I found interface INotifyPropertyChanged, but I don't know how to use it.
I agree with Matt's comments above. Here's a small piece of code to show how to implement the INotifyPropertyChanged.
===========
Code-behind
===========
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Data;
using System.Windows.Documents;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
Nicknames names;
public Window1()
{
InitializeComponent();
this.addButton.Click += addButton_Click;
this.names = new Nicknames();
dockPanel.DataContext = this.names;
}
void addButton_Click(object sender, RoutedEventArgs e)
{
this.names.Add(new Nickname(myName.Text, myNick.Text));
}
}
public class Nicknames : System.Collections.ObjectModel.ObservableCollection<Nickname> { }
public class Nickname : System.ComponentModel.INotifyPropertyChanged
{
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
void Notify(string propName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propName));
}
}
string name;
public string Name
{
get { return name; }
set
{
name = value;
Notify("Name");
}
}
string nick;
public string Nick
{
get { return nick; }
set
{
nick = value;
Notify("Nick");
}
}
public Nickname() : this("name", "nick") { }
public Nickname(string name, string nick)
{
this.name = name;
this.nick = nick;
}
public override string ToString()
{
return Name.ToString() + " " + Nick.ToString();
}
}
}
XAML
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid>
<DockPanel x:Name="dockPanel">
<TextBlock DockPanel.Dock="Top">
<TextBlock VerticalAlignment="Center">Name: </TextBlock>
<TextBox Text="{Binding Path=Name}" Name="myName" />
<TextBlock VerticalAlignment="Center">Nick: </TextBlock>
<TextBox Text="{Binding Path=Nick}" Name="myNick" />
</TextBlock>
<Button DockPanel.Dock="Bottom" x:Name="addButton">Add</Button>
<ListBox ItemsSource="{Binding}" IsSynchronizedWithCurrentItem="True" />
</DockPanel>
</Grid>
Modifying properties on the items in your collection won't fire NotifyCollectionChanged on the collection itself - it hasn't changed the collection, after all.
You're on the right track with INotifyPropertyChanged. You'll need to implement that interface on the class that your list contains. So if your collection is ObservableCollection<Foo>, make sure your Foo class implements INotifyPropertyChanged.

Resources