Silverlight mvvm dynamic controls - silverlight

How do create controls dynamically in the mvvm pattern?
The code I'm trying to port:
Parent control:
ObservableCollection History = new ObservableCollection();
private void Save_Click(object sender, RoutedEventArgs e)
{
ChildControl cc = new ChildControl();
History.Add(cc);
}

if you use ContentControl, you can simply bind to your History collection
<ListBox ItemsSource="{Binding History}">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<ContentControl Content="{Binding }"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
The above will show a list of your controls.
One thing to consider though is that with your implementation, the VM knows about View Objects, It is cleaner to use pure data in your VM and have the view worry about how to display itself.

Assuming that "ChildControl" derives from UserControl, the XAML from each of these controls will be automatically displayed when the ItemsSource is set.
<ListBox ItemsSource="{Binding History}">
</ListBox>

Related

WP7 XAML Bind to property in parent

I'm writting an app in WP7 (Silverlight 3). I have a view model that looks like this
public class MainViewModel
{
public List<ActivityTypes> ActivityTypes{get;set;}
public RelayCommand LoadActivity{get;set;}
}
My pages datacontext is set to the view model and I have a listbox with it's item source set to the ActivityTypes collection. In the listbox I'm trying to render a list of buttons who's command is bound to the LoadActivity property on the viewmodel. RelayCommand is part of the MVVM Light toolkit in case you are wondering what it is.
The problem I am having is I can't find a way to bind my button command to the LoadActivity property as my listbox has it's itemsource set to the Activitytypes collection and this property is in the parent. I've read about FindAncester but it doesn't look like this is supported in Silverlight 3.
My XAML looks like this
<UserControl.Resources>
<DataTemplate x:Key="ActivityTypeListTemplate">
<StackPanel>
<Button Command="{Binding LoadActivity}"> <!--binding not found as we're in the collection-->
<TextBlock Text="{Binding Name}" FontSize="50"/>
</Button>
</StackPanel>
</DataTemplate>
</UserControl.Resources>
<Grid x:Name="LayoutRoot" Background="{StaticResource PhoneChromeBrush}">
<ListBox Margin="0" ItemsSource="{Binding ActivityTypes}" ItemTemplate="{StaticResource ActivityTypeListTemplate}"/>
</Grid>
What's the best way to code something like this?
There is no "direct" way to do this. You can set the Buttons DataContext to your MainViewModel (preferably as a StaticResource link) and the it would work.
Take a look at Bind to parent object in xaml

Binding the ViewModel itself inside a DataTemplate with Caliburn Micro Conventions

I'm a newcomer to Caliburn.Micro and there are a few things I'm still not getting.
ViewModel first:
First of is a ViewModel that manages a Collection of other ViewModels:
public class NavigationBarViewModel : PropertyChangedBase
{
public BindableCollection<IHaveDisplayName> Items { get; set; }
}
I've got a ItemsControl (it's Telerik RadOutlookBar if that matters) as the root of a UserControl
of that view and I set the ItemTemplate too ensure that the ViewModels I insert into the collection are wrapped in a corresponding RadOutlookBarItem ( should I use ItemContainer instead of ItemTemplate here? ).
<telerik:RadOutlookBar x:Name="Items">
<telerik:RadOutlookBar.TitleTemplate>
<DataTemplate>
<ContentControl Content="{Binding Path=DisplayName}" />
</DataTemplate>
</telerik:RadOutlookBar.TitleTemplate>
<telerik:RadOutlookBar.ItemTemplate>
<DataTemplate>
<telerik:RadOutlookBarItem cal:Bind.Model="{Binding}"
Header="{Binding Path=DisplayName}">
<ContentControl />
</telerik:RadOutlookBarItem>
</DataTemplate>
</telerik:RadOutlookBar.ItemTemplate>
</telerik:RadOutlookBar>
This way I wan't the ViewModels in the collection to appear where the ContentControl is. I Bind the model to the root item of the DataTemplate to ensure conventions will work but have no idea how to bind to the ContentControl with convention. The DataContext inside the DataTemplate is of course the ViewModel itself. Using normal WPF standard I would put Content="{Binding}".
Now the model is there inside the RadOutlookBarItem but it's view doesn't get applied. Not even View can't be found, only a string with the class name.
Isn't this the proper way to do this?
As I answered here: Dynamic Telerik RadOutlookBar headers come out wrong with ItemTemplate in which I thought was a unrelated matter I was using the wrong property. ItemTemplate controls the picker and contentTemplate what comes up when you select. Here is the code that works:
<telerik:RadOutlookBar x:Name="Items">
<telerik:RadOutlookBar.ContentTemplate>
<DataTemplate >
<ContentControl cal:View.Model="{Binding}" />
</DataTemplate>
</telerik:RadOutlookBar.ContentTemplate>
<telerik:RadOutlookBar.TitleTemplate>
<DataTemplate>
<TextBlock x:Name="DisplayName"
cal:Bind.Model="{Binding}" />
</DataTemplate>
</telerik:RadOutlookBar.TitleTemplate>
<telerik:RadOutlookBar.ItemTemplate>
<DataTemplate>
<TextBlock x:Name="DisplayName"
cal:Bind.Model="{Binding}" />
</DataTemplate>
</telerik:RadOutlookBar.ItemTemplate>
</telerik:RadOutlookBar>

Trouble applying MVVM pattern

i am having some troubles applying the MVVM pattern, for start i am following this example to learn how to apply and use the pattern...
http://msdn.microsoft.com/en-us/magazine/dd419663.aspx
So my problem is establishing the "connection" between the View with the ViewModel...
In the example we have a View with a CollectionViewSource where the Source is the AllCustomers property:
<UserControl
x:Class="DemoApp.View.AllCustomersView"
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">
<UserControl.Resources>
<CollectionViewSource x:Key="CustomerGroups" Source="{Binding Path=AllCustomers}"/>
</UserControl.Resources>
<DockPanel>
<ListView AlternationCount="2" DataContext="{StaticResource CustomerGroups}" ItemsSource="{Binding}">
<ListView.View>
<GridView>
<GridViewColumn Header="Name" DisplayMemberBinding="{Binding Path=DisplayName}"/>
<GridViewColumn Header="E-mail" DisplayMemberBinding="{Binding Path=Email}"/>
</GridView>
</ListView.View>
</ListView>
</DockPanel>
</UserControl>
who belongs to the ViewModel AllCustomersViewModel:
public class AllCustomersViewModel : WorkspaceViewModel
{
(...)
public ObservableCollection<CustomerViewModel> AllCustomers { get; private set; }
(...)
}
but he uses a ResourceDictionary where he applies a DataTemplate between the View and the ViewModel:
<DataTemplate DataType="{x:Type vm:AllCustomersViewModel}">
<vw:AllCustomersView />
</DataTemplate>
but my problem is because i am not using a ResourceDictionary, and because of that i thought that i can put the DataTemplate in the Resources of the Window where i will have my View (for me is the more logic place to put the DataTemplate)... But for some reason the Data isn't appearing in the ListView, and so i ask why?
I wouldn't attach the view model in the Xaml. This hard-codes the Xaml to a specific view model.
Instead, I'd override the Application startup:
private void OnStartup(object sender, StartupEventArgs e)
{
Views.MainView view = new Views.MainView();
view.DataContext = new ViewModels.MainViewModel();
view.Show();
}
See this article:
http://www.codeproject.com/KB/WPF/MVVMQuickTutorial.aspx
This approach is also helpful if you use some sort of tool to dynamically bind your view models in the future, like MEF, Castle.Windsor or Prism.
I never bind my view models to my view in XAML. I prefer to have control over when that binding is set myself. I always put a property on the View that contains the reference to the view Model. That way I can change the view model out if needed without any unsuspecting consequences from XAML binding. Plus doing it this way allows me to put an INotify handler on the view model so all changes are updated automatically when the view model is switched.
DataTemplates without key are applied implicitly whereever data of the specified DataType is used as content that is to be displayed. That means that your ViewModel needs to appear somewhere, for example as the content of a ContentControl or an item of an ItemsControl.
So if you have a window you need to have an instance of the ViewModel in it:
<Window ...>
<Window.Resources>
<DataTemplate DataType="{x:Type vm:AllCustomersViewModel}">
<vw:AllCustomersView />
</DataTemplate>
</Window.Resources>
<Window.Content>
<vm:AllCustomersViewModel />
</Window.Content>
</Window>
Normally you only use windows as shells though, and the content is set dynamically.

Getting the SelectedItem from a combobox in a DataTemplate

Lets say I've got a DataTemplate like so
<DataTemplate x:Key="Body">
<StackPanel Orientation="Horizontal">
<ComboBox ItemsSource="{Binding Path=Person.Children}"></ComboBox>
<Button Click="Button_Click">Hello</Button>
</StackPanel>
</DataTemplate>
Which shows a list of ComboBoxes followed by a button.
Now, on clicking the button I need to discover the value in the combo next to the button pressed. I can get the data context as below but can't work out how to get the combos SelectedItem
private void Button_Click(object sender, RoutedEventArgs e)
{
// Can get the data context
var p = ((Button)sender).DataContext as Person;
// How to get the value in the combo ...?
}
you can also reference the combobox in your codebehind if you give it a name. However its cleaner to use a separate class to do your logic than the code behind. Such as a viewmodel.
then you could also do something like this...
<DataTemplate x:Key="Body">
<StackPanel Orientation="Horizontal">
<ComboBox ItemsSource="{Binding Path=Person.Children}"
SelectedItem="{Binding Path=SelectedChild}"
IsSynchronizedWithCurrentItem="True"/>
<Button Command="{Binding Path=ButtonCommand}">Hello</Button>
</StackPanel>
</DataTemplate>
Instead of using the Click event handler, use a Command and bind the CommandParameter property to the ComboBox.SelectedItem. Then in your command's executed logic, you can use the parameter.

Silverlight: How to dynamically bind a ComboBox in a ListBox ItemTemplate?

I have a list box that requires at least one ComboBox. I couldn't find a way to place the ComboBox in the ItemTemplate I use.
...
<DataTemplate x:Key="parts_template">
<StackPanel Orientation="Horizontal">
<TextBlock .../>
<ComboBox .../>
</StackPanel>
</DataTemplate>
...
<ListBox x:Name="lb_parts" ItemTemplate="{StaticResource parts_template}" .../>
...
How do bind that ComoBox in the DataTemplate to an ObservableCollection in the code behind?
Another thing you could try is subscribe the Loaded event on the ComboBox.
Then you can set the ComboBox.ItemsSource in the EventHandler to MyObservableCollection.
Have a look
XAML:
<DataTemplate x:Key="parts_template">
<StackPanel Orientation="Horizontal">
<TextBlock .../>
<ComboBox Loaded="ComboBox_OnLoaded">
<!-- ComboBox ItemTemplate -->
</ComboBox>
</StackPanel>
</DataTemplate>
C# Code Behind:
private void ComboBox_OnLoaded(object sender, EventArgs e)
{
((ComboBox)sender).ItemsSource = MyObservableCollection;
}
Okay, here is how you can add a ComboBox to the ListBox in the code behind.
Create a ComboBox
ComboBox x = new ComboBox();
If you have a data source that populates the ComboBox then you can just bind that
x.ItemsSource = e.Result;
If you do not and want to manually add items to the ComboBox:
ComboBoxItem y = new ComboBoxItem();
Set the Content of the Item to what you want displayed in the ComboBox
y.Content = "Hello";
Now all that is left, is to add the ComboBoxItem to the ComboBox (only if you are creating the Items manually), and then the ComboBox to the ListBox
x.Items.Add(y);
//testing is my ListBox
testing.Items.Add(x);
You should be able to set the data context to the List itself
lb_Parts.DataContext=myCollection;
Then you should be able to bind to it in the template
<DataTemplate x:Key="parts_template">
<StackPanel Orientation="Horizontal">
<TextBlock .../>
<ComboBox ItemSource={Binding}/>
</StackPanel>
</DataTemplate>

Resources