I have the following in C# and VS2010:
- a MainWindow.xaml with a ListView
- a MainViewModel with an ObservableCollection of objects of type, UnitData
- a UnitDataDisplay.xaml with a bunch of labels tied to members of UnitData
I need to show a variable number of UnitDataDisplays in my ListView that should be based on MainViewModel's ObservableCollection of UnitDatas. What exactly should the syntax be in XAML to bind the ListView Items to multiple UserControl objects without breaking the MVVM separation of concerns? I mean I could easily have my ObservableCollection contain a bunch of UnitDataDisplay objects but that would force my MainViewModel to have knowledge of View details.
My MainWindow XAML file looks like this:
<Window x:Class="ListViewTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="350">
<Grid>
<ListView Height="234" HorizontalAlignment="Left" Margin="12,28,0,0" Name="listView1" VerticalAlignment="Top" Width="304" ItemsSource="{Binding Path=UnitDataDisplay}"/>
</Grid>
</Window>
Any help would be greatly appreciated.
A common approach is to use implicit data templates based on model type (UnitData):
<Window.Resources>
<DataTemplate DataType="{x:Type local:UnitData}">
<local:UnitDataDisplay />
</DataTemplate>
</Window.Resources>
I would then change your ListView to a ListBox, or an ItemsControl if you don't want each item in the list to be selectable.
I would also seriously consider using an MVVM framework rather than the above approach, such as Caliburn.Micro which makes view composition such as this much easier, as well as a host of other advantages.
Related
I have a ViewModel that has a property which is a ReadOnlyObservableCollection. Defined something like this:
public class MyViewModel
{
private ObservableCollection<string> myProtectedCollection;
public ReadOnlyObservableCollection<string> MyCollectionProperty { get; }
public MyViewModel()
{
this.myProtectedCollection = new ObservableCollection<string>();
this.MyCollectionProperty = new ReadOnlyObservableCollection<string>(this.myProtectedCollection);
this.myProtectedCollection.Add("String1");
this.myProtectedCollection.Add("String2");
this.myProtectedCollection.Add("String3");
}
}
I have then created a xaml file called TestData.xaml and set the build action to DesignData. In that I have this:
<local:MyViewModel
xmlns:local="clr-namespace:ScrapWpfApplication1"
xmlns:system="clr-namespace:System;assembly=mscorlib">
<local:MyViewModel.MyCollectionProperty>
<system:String>String 1</system:String>
<system:String>String 2</system:String>
</local:MyViewModel.MyCollectionProperty>
</local:MyViewModel>
Finally I have a MainWindow.xaml with the following:
<Window x:Class="ScrapWpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:ScrapWpfApplication1"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525"
d:DataContext="{d:DesignData Source=SampleData.xaml}">
<ListBox ItemsSource="{Binding MyCollectionProperty}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Window>
The problem is that this is not showing my sample data in the Visual Studio designer. If I change the collection in my view model to be a ObservableCollection instead of a ReadOnlyObservableCollection then it works as expcted.
I guess that this is because the design time data system is creating a dummy ReadOnlyCollection but XAML is unable to populate it because it is readonly.
Is there any way to get the design type data system to work without making my view model's collection property writeable?
Is there any way to get the design type data system to work without making my view model's collection property writeable?
Yes, you could create another view model class, to be used for design purposes only, with an ObservableCollection<T> property, and set the design time DataContext of the view to an instance of this one:
d:DataContext="{d:DesignInstance Type=local:DesignTimeViewModel, IsDesignTimeCreatable=True}
I've not seen a perfect answer to this. But this is what I have finally done.
Instead of trying to get the design data system to mock the readonly collection. I've created a new set of sample data just for the collection and made the MainWindow.xaml look at that instead.
So my TestData.xaml file changes to just this. In reality it has more in it but this is just a sample for this question so it looks fairly empty.
<local:MyViewModel
xmlns:local="clr-namespace:ScrapWpfApplication1"
xmlns:system="clr-namespace:System;assembly=mscorlib">
</local:MyViewModel>
Secondly I created a second test data file called TestDataArray.xaml with an array in it. Being sure to set the build action to DesignData.
<x:Array Type="system:String"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:ScrapWpfApplication1"
xmlns:system="clr-namespace:System;assembly=mscorlib">
<system:String>String 1</system:String>
<system:String>String 2</system:String>
</x:Array>
Finally I changed my MainWindow.xaml file to this. Note the change to the binding on
<Window x:Class="ScrapWpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:ScrapWpfApplication1"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525"
d:DataContext="{d:DesignData Source=SampleData.xaml}">
<ListBox ItemsSource="{Binding}" DataContext="{Binding MyCollectionProperty}" d:DataContext="{d:DesignData Source=SampleDataArray.xaml}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Window>
This works for my particular scenario, but it would fall down if the sample data was being bound to a control and the ReadOnlyCollection was being read by something inside that control.
I made a WPF control in a library project and would like to extend it with a new one.
<UserControl x:Class="Genesyslab.Desktop.Modules.ExtensionUtils85.GUI.EmbeddingUserControl"
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="300" d:DesignWidth="300">
<Grid>
</Grid>
</UserControl>
I have tried to extend it like this:
<src:EmbeddingUserControl x:Class="Interaxalab.Desktop.Modules.PrototipoCable.CustomViews.InteractionView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:src="Genesyslab.Desktop.Modules.ExtensionUtils85.GUI"
Name="InteractionWorksheetView" Height="321.613" Width="471.396"
>
<Grid>
<WindowsFormsHost x:Name="windowsFormsHost1" HorizontalAlignment="Left" Height="284" VerticalAlignment="Top" Width="471"/>
</Grid>
</src:EmbeddingUserControl>
However, I get an error message saying that the name "EmbeddingUserControl" does not exist in namespace "Genesyslab.Desktop.Modules.ExtensionUtils85.GUI".
The name clearly does exist, since the xaml.cs can find it, but for some reason the xaml cannot.
Any help would be appreciated.
Long story short - you cannot inherit control with xaml by another control with xaml (and does it makes sense even to do so?). In your case, EmbeddingUserControl does not contain any visual tree elements (just empty grid), so you can just do:
public class EmbeddingUserControl : UserControl {
// some methods, properties of your control
}
Then you can inherit exactly like you do already in your question (don't forget to inherit from EmbeddingUserControl both in xaml file and in code-behind file).
You can also inherit from user control with xaml, if your inherited control does not have xaml itself (so you can add\override logic).
If you need to inherit some visual stuctures - you have to switch from inheritance to composition. That is: your base control provides some placeholders where other controls may be placed, or even better allows to provide templates to format data items (like for example ItemsControl and ItemTemplate property). Then you just fill those placeholders with other controls if necessary.
I am developing a Windows 8.1 apps,
and i am following MVVM Pattern
I have a Grid in the Application
<Grid Name="g1">
in which in need to add a existing User Control.
<UserControl
x:Class="CaptureApp.UIComponents.PlayVideo"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:CaptureApp.UIComponents"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="400">
<Grid>
<MediaElement Name="MediaPlay" >
</MediaElement>
</Grid>
</UserControl>
Since View (XAML) is not allowed to know the Control.
What will be the correct way to implement it??
the wordpress blog in the comments uses a datatrigger, which isn't present in windows store apps.
if I understand your question correctly, you're trying to have a view within your grid that is conditionally loaded, so that when there is no data for the user control, it is not rendered in the grid?
you could accomplish this by using a
<ContentControl Content="{Binding PropertyOnViewModel}" ContentTemplateSelector="{StaticResource SomeContentTemplateSelector}" />.
public class SomeContentTemplateSelector : DataTemplateSelector
{
public DataTemplate SomeTemplate {get;set;}
protected override DataTemplate SelectTemplate(object item, DependencyObject container)
{
if (item is null)
return null;
return SomeTemplate;
}
}
and then in a DataTemplate, have your UserControl as a child. This will display nothing when there is no Content bound to the ContentControl, and will otherwise display the supplied DataTemplate. You will need to have a property in the over-arching ViewModel that contains the content for this ContentControl, though, just fyi.
edit: if you're adding multiple items dynamically, then you will want an ObservableCollection<> property on your ViewModel, and use an ItemsControl instead of a ContentControl.
My WPF window should be able to load in different controls in same spot on the window; which should be frames to fulfill that task.
Hence i'm trying to make a frame load different pages by editing a databound string containing the Frames source. And I have managed to do that, however at the moment I have no idea how to share the frames data to the windows viewmodel hosting the frame.
I'm using MVVM and I thougth that if I could also databind a "viewmodel" to the frames datacontext, I could then both choose which page to load and which datacontext the page should use, all from the host window, therefore having access to it.
Below is my xaml.
<Window x:Class="View.Window"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window" Height="300" Width="300">
<Grid>
<Frame NavigationUIVisibility="Hidden" DataContext="{Binding WindowClass.DataContext}" Source="{Binding WindowClass.FrameURI}"/>
</Grid>
However, if I now assign the pages datacontext through this binding, instead of in the code behind, nothing gets loaded. Now I basically end up with a blank frame.
Why?
You can use Window.Resources to bind to your DataContext, then Bind to the FrameURI (You'll need to fix the appropriate namespace instead of my custom xmlns:WindowClass):
<Window x:Class="View.Window"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:WindowClass="clr-namespace:WindowClass"
Title="Window" Height="300" Width="300">
<Window.Resources>
<WindowClass:MyViewModelName/>
</Window.Resources>
<Grid>
<Frame NavigationUIVisibility="Hidden" DataContext={Binding} Source="{Binding FrameURI}"/>
</Grid>
You can find a very basic tutorial here
I defined an object which contains properties in code-behind and, want to set the object to datacontext in xaml.
namespace WpfApplication4
{
public partial class MainWindow : Window
{
public EquipInfo equip1;
public MainWindow()
{
InitializeComponent();
equip1 = new EquipInfo();
// setting here works fine but i want to do in xaml
//textBox1.DataContext = equip1;
}
}
}
here's xaml code..
<Window x:Class="WpfApplication4.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">
<Grid>
<TextBox Text="{Binding Path=PIN}" Height="23"
HorizontalAlignment="Left" Margin="172,208,0,0"
Name="textBox1" VerticalAlignment="Top" Width="120" />
</Grid>
</Window>
You can set the DataContext via XAML to a public property. blindmeis has given a good example on how to do this.
What you did in your Post was not setting the DataContext, but binding the Text Property of your Control to a Property of the window. This only works if a DataContext is set. Another way to do that, if you don't want to do MVVM (which I'd recommend, though), is referencing specific Elements in your Binding:
1.) Alter member to AutoProperty or similar
public EquipInfo equip1 {get;set;}
2.) Give your window a name
<Window x:Class="WpfApplication4.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Name="myWin"
Title="MainWindow" Height="350" Width="525">
2.) Access Window Properties by instance name
<TextBox Text="{Binding ElementName=myWin, Path=equip1.PIN}"/>
On a side note, it would really be better to use a MVVM instead.
when you create your equipinfo class in codebehind why not setting the datacontext there?
nevertheless you can create a datacontext in xaml (you did not need the codebehind stuff then)
<TextBox Text="{Binding Path=PIN}">
<TextBox.DataContext>
<local:equip1/>
</TextBox.DataContext>
</TextBox>
but please look at the MVVM pattern
When you create your equipinfo class in codebehind why not setting the datacontext there?
The whole point of MVVM is to seperate UI from code behind using a viewmodel proxy. If you are going to reference the ui element to set its datacontext you might just as well reference it to set its value and forget about mvvm.