I'm having an application using MVC. It has a canvas and property grid. When an item is selected in the canvas. The property grid should display its details.
So I made an event listener and when item is selected in the canvas it raises an event to the controller which pass the selected item to the property grid to display the details.
Model :
Item object containing name, description
Controller :
protected Controller(object model, FrameworkElement view)
{
this._model = model;
this._view = view;
}
public virtual void Initialize()
{
View.DataContext = Model;
}
View :
<TextBlock>Status</TextBlock>
<ComboBox ItemsSource="?????"/>
Where view is the property grid and model is the selected item.
The problem is in the property grid there is a dropdown list containing lookup values how can I get the dropdown values given that the datacontext of the property grid has already been set to the selected item which doesn't contain reference to these lookup items.
I know that it's easy to use custom code to do that. But I don't want to violate the MVC aproach.
Bind to a source rather than DataContext, sources are provided by ElementName, RelativeSource & Source, so you can name the View for example and use ElementName to get it as source then the Path could be DataContext.LookupValues or whatever your property in the model (- the DataContext of the View is your model -) is called.
e.g.
<Window ...
Name="Window">
<ItemsControl ItemsSource="{Binding Items}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Name}" />
<ComboBox ItemsSource="{Binding ElementName=Window, Path=DataContext.Occupations}"
SelectedItem="{Binding Occupation}" />
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<!-- ... --->
Edit: Your problem seems to be that you do not pass the information you need, consider a design which still grants you access to more than just the SelectedItem of some list, e.g.
<Window ...
Name="Window">
<ListBox Name="listBox" ItemsSource="{Binding Data}" />
<ContentControl DataContext="{Binding ElementName=listBox, Path=SelectedItem}">
<ComboBox ItemsSource="{Binding ElementName=Window, Path=DataContext.Occupations}"
SelectedItem="{Binding Occupation}" />
</ContentControl>
<!-- ... --->
The DataContext of the ContentControl may be the SelectedItem of the ListBox but the ComboBox inside can still reference the DataContext of the Window which should provide the necessary information.
This is similar to my first example in that the DataContext inside the DataTemplate is always an item of the collection but you can access external DataContexts using sources in your bindings.
Related
I'd like to bind the SelectedItem of a TabControl to a corresponding field in my view model, however while still declaring the available items within the TabControl itself (as opposed to using ItemsSource) and retrieving their Content as for the actual SelectedItem. Meaning: If a tab is being selected, it's Content should end up as the SelectedItem (not the TabItem) and vice-versa.
Sample view model, inheriting a Caliburn.Micro conductor without (!) collection:
public class MyViewModelConductor : Conductor<ConductedViewModelBase> {
public ViewModelA { get; set; }
public ViewModelB { get; set; }
}
And the corresponding TabControl in XAML:
<TabControl SelectedItem="{Binding ActiveItem}">
<TabItem cal:View.Model="{Binding ViewModelA}">
<TabItem.Header> <!-- vm specific fancy UI stuff --> </TabItem.Header>
</TabItem>
<TabItem cal:View.Model="{Binding ViewModelB}">
<TabItem.Header> <!-- vm specific fancy UI stuff --> </TabItem.Header>
</TabItem>
</TabControl>
I'm aware I could just use e.g. Conductor<'1>.Collection.OneActive and bind to ItemsSource, but there are a few reasons I'd like to refrain from doing so:
The available view models from the conductor's side is a fixed set, declared by the exposed properties, not an infinite collection
For the UI's side, for each TabItem I need to declare a specific header with lots of just UI related stuff (icon, color) which is platform-specific, hence I would not like to leak it into my view models.
I've tried utilizing SelectedValue and SelectedValuePath and binding to the TabControl itself (e.g. SelectedValue="{Binding RelativeSource={RelativeSource Self}, Path=SelectedItem}" SelectedValuePath="Content"), but there WPF tries to look for a Content property on my bound view models as soon as one becomes selected.
You would have to bind the SelectedValue to your view model class. Then use the SelectedValuePath to declare which property of the SelectedItem is used as the SelectedValue.
<TabControl SelectedValuePath="Content"
SelectedValue="{Binding ViewModelSelectedContentProperty}">
<TabItem cal:View.Model="{Binding ViewModelA}">
<TabItem.Header> <!-- vm specific fancy UI stuff --> </TabItem.Header>
</TabItem>
<TabItem cal:View.Model="{Binding ViewModelB}">
<TabItem.Header> <!-- vm specific fancy UI stuff --> </TabItem.Header>
</TabItem>
</TabControl>
But I don't recommend this. You should bind the ItemSource to a set of data models and define DataTemplates to give you a clean design and dynamic/extensible behavior.
Usually you would use DataTemplate for the TabControl.ContentTemplate to template the content and TabControl.ItemTemplate to template the TabItem (TabControl header).
Don't hardcode the ItemsControl items. They're is absolutely no reason to avoid data templating.
I have a class PricingData and PricingSchedule. Where PricingSchedule is a List<> inside PricingData class. I want to bind data of this class to UWP controls.
Sample code is available to download here : https://github.com/jigneshdesai/SampleOfBindingIssue1.git
How Code looks: i have a start page(mainpage) that hosts ListView control, Listview has PricingUserControl within it. PricingUserControl looks like this
<TextBlock x:Name="lblPriceHeader" Text="{Binding PricingTitle}" Margin="0,0,50,0" />
<ComboBox x:Name="cbPriceValueList" ItemsSource="{x:Bind dpl}" DisplayMemberPath="PriceValue" SelectedValuePath="PriceValue" SelectedValue="{Binding DisplayPricing}" />
<ListView x:Name="lbPriceChangeSchedule" ItemsSource="{Binding PricingScheduleList}">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel>
<StackPanel Orientation="Horizontal">
<ComboBox x:Name="cbSchedulePriceValueList" ItemsSource="{x:Bind dpl}" DisplayMemberPath="PriceValue" SelectedValuePath="PriceValue" />
<TextBlock Text="{Binding SchedulePricingTimeZone }" />
</StackPanel>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
What i want to achieve: Combobox should populate a list of values (eg. 1USD, 2USD, 3USD etc.). Then when you provide List of records from database, the listbox will repeat PricingUserControl and combobox within it should set its value property (SelectedValue) as per record.
Issue:
ComboBox x:Name="cbPriceValueList" uses x:bind dpl where dpl is a local variable of PricingUserControl. It populates the list properly. The trouble is ComboBox x:Name="cbSchedulePriceValueList" it also has x:bind dpl but during compilation it display error "Invalid binding path 'dpl' : Property 'dpl' not found on type 'DataTemplate'."
I am wondering why x:bind dpl does not work at this point. ?
I have now realized that your problem is in fact that you need to reach to a Page property from within the DataTemplate, so here is a updated answer.
You cannot use x:Bind if you need to access an outside element's property from within a DataTemplate. Instead, you can use classic {Binding} expression. First add a name to your page:
<Page
...
x:Name="Page">
And now refer to this name from within the DataTemplate:
<ComboBox
x:Name="cbSchedulePriceValueList"
ItemsSource="{Binding ElementName=Page, Path=dpl}"
DisplayMemberPath="PriceValue"
SelectedValuePath="PriceValue" />
Original answer
To be able to use x:Bind inside of a DataTemplate, you must specify the data type the individual items of the control will have, using x:DataType. Suppose your PricingScheduleList is a List<MyApp.Models.MyType>, then you will first need to add this XML namespace to the <Page> element:
xmlns:models="using:MyApp.Models"
And then set the x:DataType attribute as follows:
<DataTemplate x:DataType="models:MyType">
...
</DataTemplate>
You can confirm this works by the fact that IntelliSense should now suggest you the properties of MyType when you start writing the x:Bind expression.
By checking your code, the reason why SelectedValue does not take effect is when you choose the item from ComboBox, you didn't notify your DisplayPricing to change. So you need to implement INotifyPropertyChanged interface in your PricingData. Do the same behavior in PricingSchedule.
public class PricingData : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged = delegate { };
......
public string DisplayPricing
{
get => $"{PricingValue} {PricingCurrency}";
set
{
var sp = value.Split(' ');
PricingValue = sp.First();
PricingCurrency = sp.Last();
OnPropertyChanged();
}
}
public void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
PScheduleUserControl.xaml:
<ComboBox x:Name="cbPriceValueList" ItemsSource="{x:Bind myList}" DisplayMemberPath="PriceValue" SelectedValuePath="PriceValue" SelectedValue="{Binding DisplayPricing,Mode=TwoWay}" />
I am trying to bind a ListBox to another ListBox within the same window. The left hand sided Listbox has data in it that one can select. But I want a user to be able to click on the item(s) in the left hand listbox and those same item(s) would be displayed in the other listbox on the right hand side.
EDITED: Of course you can bind a UI property to another UI property (Dependency Property actually) using ElementName, but I recommend to bind the properties to one view model. See a simplified example below.
View model:
public ObservableCollection<ItemObject> Items { get; set; }
public ObservableCollection<ItemObject> SelectedItems { get; set; }
Left:
<ListBox ItemsSource="{Binding Items}" SelectedItems="{Binding SelectedItems}" />
(Note that there is no SelectedItems dependency property actually. See question like: Select multiple items from a DataGrid in an MVVM WPF project)
Right:
<ListBox ItemsSource="{Binding SelectedItems}" />
This works fine. Furthermore, with this approach, the list on the right hand can be customized with ease (eg order, filter, ... by using CollectionView).
private ICollectionView _collectionView;
private ICollectionView _CollectionView {
get { return _collectionView
?? (_collectionView = CollectionViewSource.GetDefaultView(SelectedItems)); }
}
public ICollectionView FilteredItems {
get { _CollecitionView.Filter(...); }
}
<ListBox ItemsSource={"Binding FilteredSelectedItems"} />
Such an MVVM approach is sometimes laborious, but eventually found as beneficial.
You name the first listbox, then any other control on the xaml will bind to that control using it's name in the ElementName attribute of the binding.
For example there are two listboxes and one text box. The top listbox has multiselections and those selection(s) are shown on the lower listbox. While the textbox only gets the first item selected.
<StackPanel Orientation="Vertical">
<StackPanel.Resources>
<converters:PathToFilenameConverter x:Key="FilenameConverter" />
<x:Array x:Key="FileNames" Type="system:String">
<system:String>C:\Temp\Alpha.txt</system:String>
<system:String>C:\Temp\Beta.txt</system:String>
<system:String>C:\Temp\Gamma.txt</system:String>
</x:Array>
</StackPanel.Resources>
<ListBox Name="lbFiles"
SelectionMode="Multiple"
ItemsSource="{StaticResource FileNames}"
Margin="10"/>
<ListBox ItemsSource="{Binding SelectedItems, ElementName=lbFiles }" Margin="10" />
<TextBlock Text="{Binding SelectedItem,
ElementName=lbFiles,
Converter={StaticResource FilenameConverter}}"
Margin="10" />
</StackPanel>
Note...the code is binding using the SelectedItems property for the lower list box and not SelectedItem used by the TextBlock.
As an aside, another answer has the use of an ObservableCollection, that is not needed unless the array is dynamically changing; otherwise any array can be used. Depending on loading, say from a VM, it may need to adheres to the INotifyPropertyChanged.
I have a wpf programme with a main View (Window)which contains a TabControl to show several different UserControl Views (the sub-views, one in each tab). Every View has an associated ViewModel.
I wish to bind the TabControl so that I just need to load a new sub-view into the ApplicationViewModel and it will appear on the TabControl.
I have successfully bound the sub-views to the content, but cannot seem to get anything in the header. I wish to bind the header to a property in the sub-view's ViewModel, specifically TabTitle.
Application View (DataTemplate binding not working):
<Window ...>
<DockPanel>
<TabControl ItemsSource="{Binding PageViews}" SelectedIndex="0"> <!--Working-->
<TabControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding DataContext.TabTitle}, Path=DataContext.TabTitle}" /> <!--Not Working-->
</DataTemplate>
</TabControl.ItemTemplate>
</TabControl>
</DockPanel>
</Window>
Application ViewModel (ObservableObject basically implements INotifyPropertyChanged`):
class ApplicationViewModel : ObservableObject
{
private DataManager Data;
private ObservableCollection<UserControl> _pageViews;
internal ApplicationViewModel()
{
Data = new DataManager();
PageViews.Add(new Views.MembersView(new MembersViewModel(Data.DataSet)));
}
public ObservableCollection<UserControl> PageViews
{
get
{
if (_pageViews == null)
{
_pageViews = new ObservableCollection<UserControl>();
}
return _pageViews;
}
}
The MembersView Code behind:
public partial class MembersView : UserControl
{
public MembersView(MembersViewModel ViewModel)
{
InitializeComponent();
DataContext = ViewModel;
}
}
MembersViewModel (truncated):
public class MembersViewModel : INotifyPropertyChanged
{
public TabTitle { get; protected set; }
public MembersViewModel(DataSet BBDataSet)
{
TabTitle = "Members";
}
//All view properties
}
I'm sure that it is something simple...
You are binding the TabControl to a collection of type UserControl. That means the data context for each item will be of type UserControl. There is no property named "TabTitle" in UserControl, so the binding will not work.
I think what you are trying to do can be accomplished with the following changes:
Have ApplicationViewModel expose a collection of type MembersViewModel, instead of UserControl, and populate it appropriately.
Setup a ContentTemplate to create views for your items in the TabControl:
<TabControl.ContentTemplate>
<DataTemplate DataType="{x:Type namespace:MembersViewModel}">
<namespace:MembersView />
</DataTemplate>
</TabControl.ContentTemplate>
(Replace "namespace:" with your xaml imported namespace containing your controls.)
Update the ItemTemplate in your TabControl so it binds properly to the view model:
<TabControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding TabTitle}}" />
</DataTemplate>
</TabControl.ItemTemplate>
Update MembersView to have a parameterless constructor. The DataContext on the view will be set for you by the TabControl. If you need to access the view model from your code-behind, it should be available through the DataContext property after the InitializeComponent() call.
Anytime you are working with ItemsControl (and its extensions such as ListBox, TreeView, TabControl, etc.), you should never be instantiating your own item views. You always want to setup a template that instantiates the view based on the data (or view model) and bind directly to the data (or view model) in the ItemsSource property. This allows all of the item's data contexts to be setup for you so you can bind to them.
Edit: Since you have multiple view / viewmodel pairings, you will want to define your templates slightly differently:
<TabControl ItemsSource="{Binding PageViews}" SelectedIndex="0">
<TabControl.Resources>
<DataTemplate DataType="{x:Type namespace:MembersViewModel}">
<namespace:MembersView />
</DataTemplate>
<DataTemplate DataType="{x:Type namespace:ClassesViewModel}">
<namespace:ClassesView />
</DataTemplate>
<DataTemplate DataType="{x:Type namespace:SessionsViewModel}">
<namespace:SessionsView />
</DataTemplate>
</TabControl.Resources>
<TabControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding TabTitle}}" />
</DataTemplate>
</TabControl.ItemTemplate>
</TabControl>
The difference is that you want to define multiple data templates, one for each type, in your resources. That means it will use those templates each time it encounters those types. You still want to set ItemTemplate to force the tab headers to use a specific template. However, do not set ContentTemplate, allowing the content to use the data templates defined in resources.
I hope that makes sense.
P.S. You can also define these data templates in a higher level resource dictionary, such as in your main window or your application, if you want them to apply to content presenters every place you use those view models, rather than only in this one TabControl.
I have a DataTemplate for templating my ItemsControl's items which are TimeSheet's Details.
I have couple of TextBox representing certain values of my TimeSheet's Details but their IsEnabled property depends on the TimeSheet itself, not the details.
<ItemsControl
ItemsSource="{Binding Path=TimeSheet.TimeSheetDetails}"
ItemTemplate="{StaticResource TimeSheetDetail}"
/>
<DataTemplate x:Key="TimeSheetDetail">
<TextBox
Text="{Binding Houre}"
IsEnabled="Binding ??????">
</DataTemplate>
Since the IsEnabled property cant be found in the TimeSheetDetails but can be found in my ViewModel, i would like to bind directly to my ViewModel's Property but when i try binding, to my ViewModel from my DataTemplate, it only seems to look in my TimeSheetDetail.
How can i access my ViewModel's public property directly?
You can bind to your parent's DataContext:
{Binding DataContext.IsEnabled,
RelativeSource={RelativeSource FindAncestor, AncestorType=ItemsControl}}