how to build dynamic grid and binding to xaml using mvvm - wpf

I'm planning a WPF application which will build dynamic grid with textblocks in the viewmodel and then refresh interface (xaml) with the new grid.
I've done the firts step, but i have problems to refresh the view with the new grid.
Is there any example code of how to bind the grid to the xaml that I can have a look at?? I really can't figure this out!
Thanks

You may be approaching this slightly wrongly, hard to say from the question-
Generally to show a dynamic set of UI elements in MVVM you bind the ItemsSource property of an ItemsControl to an ObservableCollection. The ItemsControl ItemsTemplate property converts the YourViewModel object into a UIElement which can be a TextBlock or whatever style you want.
So as an example:
// model
class Person
{
public string Name {get; private set;}
}
// view model
class MainViewModel
{
public ObservableCollection<Person> People {get; private set;}
}
//view
<UserControl DataContext="{Binding MyMainViewModelObject}">
<ItemsControl ItemsSource="{Binding People}">
<ItemsControl.ItemsTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"/>
</DataTemplate>/
</ItemsControl.ItemsTemplate>
</ItemsControl>
</UserControl>
I havent tested that code, it is just to illustrate. There are other ways of dissecting the problem into MVVM, it all depends on the situation. You would have to give more details for us to help you out with that. Rarely in WPF is there a need to use code to create or add UI elements to other UIElements etc.
A point to note more along the exact lines of the question however is that an ItemsControl can either bind to a bunch of regular objects and use it's template to create UIElements from them, OR it can bind to a list of UIElements, in which case the template is not applied (sounds like this is the situation you have).

Related

Adding controls dynamically in WPF MVVM

I am working on a dynamic search view wherein clicking a button should add a new row containing 3 combobox and 2 textboxes.
How should I go about doing this?
If you really want to do mvvm , try to forget "how can I add controls". You don't have to, just think about your viewmodels - WPF create the contols for you :)
In your case lets say we have a SearchViewModel and a SearchEntryViewmodel.
public class SearchEntryViewmodel
{
//Properties for Binding to Combobox and Textbox goes here
}
public class SearchViewModel
{
public ObservableCollection<SearchEntryViewmodel> MySearchItems {get;set;}
public ICommand AddSearchItem {get;}
}
Till now you dont have to think about usercontrols/view. In your SearchView you create an ItemsControl and bind the ItemsSource to MySearchItems.
<ItemsControl ItemsSource="{Binding MySearchItems}"/>
You see now all of your SearchEntryViewmodels in the ItemsControl(just the ToString() atm).
To fit your requirements to show every SearchEntryViewmodel with 3Comboboxes and so on you just have to define a DataTemplate in your Resources
<DataTemplate DataType="{x:Type local:SearchEntryViewmodel}">
<StackPanel Orientation="Horizontal">
<Combobox ItemsSource="{Binding MyPropertyInSearchEntryViewmodel}"/>
<!-- the other controls with bindings -->
</StackPanel>
</DataTemplate>
That's all :) and you never have to think about "how can I add controls dynamically?". You just have to add new SearchEntryViewmodel to your collection.
This approach is called Viewmodel First and I think it's the easiest way to do MVVM.
One option is that you can create TextBoxes and comboboxes in backend by creating a new instanse.
But the better option is that you can create one usercontrol which contains All texboxes and comboboxes which you want to add and in which format you want.
After creating when the button is pressed you can create a instace of this usercontrol and set it in the grid or any other control by using SetValue property of the control.
If you are new to WPF and MVVM this read this blogs to understand this.
https://radhikakhacharia.wordpress.com/2012/06/01/wpf-tutorial-3/
https://radhikakhacharia.wordpress.com/2012/02/13/model-view-viewmodel/
If you are new to both MVVM and WPF, there is a really wonderful video tutorial on how to
architect a C# / WPF / MVVM application by Jason Dollinger which is available here on lab49. All of the sourcecode he developes in this amazing video is available also right here on lab49.
After watching it, you will not have any problems developing your search view for sure.

How do I bind a "list" of strings to a ComboBox in WPF?

I basically want to take a bunch of names in a collection and bind them to a combobox. For example:
Bill
Jack
Bob
Kevin
and have those items in a collection and have it bound to the ComboBox. I'm not sure if the list will be updated dynamically or not, but I prefer to plan for it to be. Any help would be appreciated. I've been trying for a few hours now and can't figure it out. I want to do it in XAML and not the code-behind. In the code-behind,
MyComboBox.ItemsSource = MyObservableCollection;
works fine. I don't know how to do that in XAML though with the collection declared in the code-behind.
Thanks in advance (again), community.
*EDIT:
This is how I have the collection declared and accessible.
public ObservableCollection<string> propertynames
{
get {return _propertynames;}
}
private ObservableCollection<string> _propertynames;
The last thing I tried was this:
<Window.Resources>
<CollectionViewSource Source="{Binding propertynames}" x:Key="srcSort"/>
</Window.Resources>
....
<ComboBox x:Name="cboSort" HorizontalAlignment="Left" VerticalAlignment="Top"
Width="256" Background="WhiteSmoke" Margin="12,50,0,0" FontSize="12pt"
Height="27.28"
SelectedIndex="0"
SelectionChanged="cboWorkCenters_SelectionChanged"
ItemsSource="{Binding Path = {StaticResource srcSort}}">
</ComboBox>
....
I'm a total n00b to this stuff. Been in it about a week now, so I may have done something really obvious to a seasoned user.
*EDIT #2
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:s="clr-namespace:WpfApplication1"
Title="Window1" Height="226" Width="242"
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Grid>
<ComboBox Margin="43,71,40,77"
Name="comboBox1"
ItemsSource="{Binding ob}" />
</Grid>
</Window>
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public ObservableCollection<string> ob
{
get
{
return _ob;
}
}
private ObservableCollection<string> _ob = new ObservableCollection<string>();
public Window1()
{
InitializeComponent();
FillObj();
//comboBox1.ItemsSource = ob;
}
private void FillObj()
{
for (int i = 1; i < 6; i++)
{
_ob.Add(i.ToString());
}
}
}
}
Made above real simple project just to see if I was doing it all wrong. This worked fine so something else must be causing it to fail.
*EDIT #3
*PROBLEM FIXED
For God's sake, I figured it out. I've been on this for HOURS and it's just silly what's caused it to fail.
The solution is this: I wasn't instantiating _propertynames when I declared it. I was querying the class properties with Linq to get the list of properties and then created _propertynames by passing ...GetProperties.ToList<...>() to the constructor. Apparently, you have to instantiate the variable so it hits during InitializeComponent. Unreal.
Once I did that and then added the items to it after the fact, it worked fine.
I wish WPF had a face so I could punch it. I know it's my ignorance of how it works, but I really could have used some kind of message.
Thanks guys for the help. Both of your suggestions were useful once I took care of the root issue.
private ObservableCollection<string> _propertynames
needs to be
private ObservableCollection<string> _propertynames = new ObservableCollection<string>()
There are countless ways of doing this. Once you've created the collection in code-behind, you can:
Call Resources.Add to add it to the window's resource dictionary, and then bind to the resource, e.g. ItemsSource="{Binding {DynamicResource MyList}}".
Give the ComboBox a name (using the x:Name attribute) and set its ItemsSource explicitly in code, e.g. MyComboBox.ItemsSource = myCollection;.
Create a class, make the collection a property of the class, and set the window's DataContext to an instance of that class and bind to it directly, e.g. ItemsSource = "{Binding MyCollectionProperty}".
Make the collection a property of the window, set the window's DataContext to this, and bind to the property (this is essentially the same technique as #3, only you're not creating a new class).
Without setting the window's DataContext, you can still reference a property on it using binding as long as you've given it a name, e.g. {Binding ElementName=MyWindow, Path=MyCollection}. (This is the same as Ross's suggestion.)
Or, without giving the window a name, you can use RelativeSource binding to find the ancestor Window and bind to a property on it. I don't have any confidence in my ability to write a working binding expression that uses RelativeSource off the top of my head, so I'll leave that as an exercise for the reader.
You can set the DataContext of the ComboBox to the instance of your collection, and then set itsItemsSource to {Binding}. You probably wouldn't do this in practice; I mention it just because it seems to be a common mistake for people to set the DataContext of a control without also setting a binding, and then wonder why content from the bound object isn't showing up.
(While I've said "window" in the above, everything I've said is also true for user controls.)
I'm sure there are at least five other ways to do this that I'm not thinking of. Binding is really, really flexible.
What have you tried so far?
I would approach it as follows, assuming the combo box is within a UserControl with a code-behind class containing the public property MyObservableCollection:
<UserControl x:Name="MyCollectionOwnerControl">
<ComboBox ItemsSource="{Binding ElementName=MyCollectionOwnerControl, Path=MyObservableCollection, Mode=OneWay}" />
</UserControl>

binding to observable collection silverlight 4, grid

Can I bind a simple 'grid' to an observable collection? So i have a grid with just one column and several rows. The rows get populated at runtime with some hyperlinks which can get deleted/added etc. I don't want to write functions to add/remove them from the grid everytime and would prefer to use an observable collection and let the grid update itself. Can a simple grid do that ? i tried but it didn't even compile.
Thanks
[EDIT] Solved. The marked answer is correct [/EDIT]
Other answers cover various bases but your specific requirement is filled by the ItemsControl. You would probably want to contain it in ScrollViewer just in case where you have more links than can be seen at one time. You would have markup something like this:-
<ScrollViewer>
<ItemsControl ItemsSource="{Binding MyObsCollectionOfUrlInfo">
<ItemsControl.ItemTemplate>
<DataTemplate>
<HyperLinkButton NavigateUri={Binding Uri} Content={Binding Title} />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
Your observable collection would contain a list of objects of a type like:-
public class UrlInfo
{
public Uri Uri {get; set; }
public string Title {get; set; }
}
Silverlight does not support this. You have two options, either use a DataGrid or use the following code that allows you to use a Grid within an ItemsControl which will achieve what you are after.
http://www.scottlogic.co.uk/blog/colin/2010/11/using-a-grid-as-the-panel-for-an-itemscontrol/
#ColinE is correct, you can't bind to a Grid, but you can bind an ObservableCollection to a DataGrid or an ItemsControl.

WPF: use a ListBox in a template that will be the template of another ListBox

I have a ListBox whose ItemSource is an ObjectDataProvider that is an instance of an ObservableCollection. The ObservableCollection is a collection of ObservableCollections. The ItemTemplate of the ListBox is a DataTemplate that creates a ListBox for each item of the listbox. To illustrate this better I'm trying to recreate a card game in WPF. Basically, from a hand of cards you can create books. After you have a valid book, you can elect to make it a book which will go into the ObservableCollection of Books. The problem that I'm having is that each item of the ListBox is a ListBox that has an ItemSource that is a Book, that is an ObservableCollection of Cards. I don't think I'm having a problem with the source or the template of the outer ListBox, but I'm having a hard time understanding how I'm going to set the source of the ListBox items to the collection of cards for each book. Essentially, my question may be confusing and a difficult concept to grasp, but essentially I'm trying to figure out how to use a ListBox in a template that will be the template of another ListBox. If anyone has any idea of how to approach this, I would greatly appreciate hearing it.
With Card like the following:
public class Card
{
private string _name;
public Card(string name)
{
_name = name;
}
public string Name
{
get { return _name; }
set { _name = value; }
}
}
and Book like the following:
public class Book
{
private readonly ObservableCollection<Card> _cards;
public Book(ObservableCollection<Card> cards)
{
_cards = cards;
}
public ObservableCollection<Card> Cards
{
get { return _cards; }
}
}
Then create your ListBox in the window:
<ListBox
ItemsSource="{Binding ElementName=Window, Path=Books}"
ItemTemplate="{StaticResource MainListTemplate}" />
and in the resources for the window put:
<Window.Resources>
<ResourceDictionary>
<DataTemplate
x:Key="InsideListTemplate">
<TextBlock
Text="{Binding Name}" />
</DataTemplate>
<DataTemplate
x:Key="MainListTemplate">
<ListBox
ItemsSource="{Binding Cards}"
ItemTemplate="{StaticResource InsideListTemplate}" />
</DataTemplate>
</ResourceDictionary>
</Window.Resources>
Your ListBox uses the MainListTemplate, which contains a ListBox. The ItemsSource for that ListBox is your list of Cards, and the ItemTemplate is the InsideListTemplate. I have it as a simple TextBlock but you could do whatever you need.
Don't put a ListBox inside a ListBox, it will create a very confusing UI because you'll have several "levels" of selected items.
You can put an ItemsControl inside a ListBox if you need a single ListBox with a collection inside each item or a ListBox inside an ItemsControl if you need multiple list boxes.
Thank you for the responses. While I do agree with both responses, and always appreciate being notified of bad coding practices, the first answer did the trick. I was having an issue with the ItemsSource of the ListBox within my DataTemplate. Somewhere along the lines of learning WPF, I became hooked on using ObjectDataProvider(s) as my ItemsSource. Since the ObjectDataProvider was only an instance of the collection, and when I would update it the source of cards for all of my "Books" would be the same. Changing my ItemsSource binding source directly to the observable collection "Cards" did the trick.
Although it may be confusing in regards to the UI, I'm not sure that I'm going to even allow for the items in either of the lists to be selectable. My intentions were merely for a visual representation of the players books. I may need to allow for the items on the outer list to be selectable in able to move the cards from a book and back to the main hand but I'm not sure yet.
Thanks again for the help.
Thanks,
Brandon

WPF Databinding

Can anyone point me to a good resource (or throw me a clue) to show me how to do DataBinding to controls (ComboBox, ListBox, etc.) in WPF? I'm at a bit of a loss when all my WinForms niceities are taken away from me, and I'm not all that bright to start with...
The best resource I've found for WPF data binding is Bea Costa's blog. Start from the first post and read forward. It's awesome.
I find the tutorial videos at Windows Client .Net equally awesome. Dot Net Rocks TV has also covered it some time ago.
in code behind -- set the DataContext of your list box equal to the collection you're binding to.
private void OnInit(object sender, EventArgs e)
{
//myDataSet is some IEnumerable
// myListBox is a ListBox control.
// Set the DataContext of the ListBox to myDataSet
myListBox.DataContext = myDataSet;
}
In XAML, Listbox can declare which properties it binds to using the "Binding" syntax.
<ListBox Name="myListBox" Height="200"
ItemsSource="{Binding Path=BookTable}"
ItemTemplate ="{StaticResource BookItemTemplate}"/>
And some more links, just in case the above didn't suffice:
Windows Presentation Foundation - Data Binding How-to Topics
- Approx 30 'How To' articles from MSDN.
"The topics in this section describe how to use data binding to bind elements to data from a variety of data sources in the form of common language runtime (CLR) objects and XML. "
Moving Toward WPF Data Binding One Step at a Time
- By WPF guru Josh Smith
"This article explains the absolute basics of WPF data binding. It shows four different ways how to perform the same simple task. Each iteration moves closer to the most compact, XAML-only implementation possible. This article is for people with no experience in WPF data binding."
Here's another good resource from MSDN: Data Binding Overview.
There are three things you need to do:
Bind the ItemsSource of the ComboBox to the list of options.
Bind the SelectedItem to the property that holds the selection.
Set the ComboBox.ItemTemplate to a DataTemplate for a ComboBoxItem.
So, for example, if your data context object is a person having email addresses, and you want to choose their primary, you might have classes with these signatures:
public class EmailAddress
{
public string AddressAsString { get; set; }
}
public class Person
{
public IEnumerable<EmailAddress> EmailAddresses { get; }
public EmailAddress MainEmailAddress { get; set; }
}
Then you could create the combo box like this:
<ComboBox ItemsSource="{Binding EmailAddresses}" SelectedItem="{Binding MainEmailAddress}">
<ComboBox.ItemTemplate>
<DataTemplate>
<ComboBoxItem Content="{Binding AddressAsString}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
Now you need to implement INotifyPropertyChanged in both Person and EmailAddress. For the EmailAddresses collection, you could back it with an ObjservableCollection.
Or as an alternative you can use Update Controls .NET. This is an open source project that replaces data binding and does not require INotifyPropertyChanged. You can use whatever collection makes sense to back the EmailAddresses property. The XAML works the same as above, except that you import the UpdateControls.XAML namespace and replace {Binding ...} with {u:Update ...}.

Resources