MVVM Listbox in tab control is not updating - c#

I'm struggling with update issue. I have tab control with the listbox binded to an Observable Collection
ListBox HorizontalAlignment="Center" Height="450" VerticalAlignment="Top" Width="250"
x:Name="LbxMenu" Background="{x:Null}" BorderBrush="{x:Null}"
ItemsSource="{Binding TestListsNames}" FontFamily="Segoe UI Semilight" FontSize="18"/>
view model:
private ObservableCollection<string> _testListsName;
public ObservableCollection<string> TestListsNames
{
get { return _testListsName; }
set{ _testListsName = value; }
}
After inserting entity to database there is an event which invokes TestListInitialize method in my ViewModel which should refresh collection and it works as I can see it in debugger. But listbox doesn't refresh and I have to restart application to see changes.
It worked great when it was in separate window but when I changed ui to tab control it doesn't.
Update function:
private void TestListNamesInitialize()
{
TestListsNames = db.GetTestListNamesFromDatabase();
if (TestListsNames.Count != 0) CanLoad = true;
}
Initial Window:
<Controls:MetroWindow
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="Test.View.InitialWindow"
xmlns:Controls="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro"
xmlns:tabdata="clr-namespace:Test.View.TabItems"
Title="Testownik" Height="600" Width="900" ShowTitleBar="True" ResizeMode="NoResize" Icon="../GraphicResources/Icon.ico">
<Controls:MetroWindow.RightWindowCommands>
<Controls:WindowCommands>
<Button Content="settings" />
<Button>
<StackPanel Orientation="Horizontal">
<TextBlock Margin="4 0 0 0"
VerticalAlignment="Center"
Text="about" />
</StackPanel>
</Button>
</Controls:WindowCommands>
</Controls:MetroWindow.RightWindowCommands>
<Controls:MetroAnimatedTabControl x:Name ="MainTabControl">
<TabItem Header="Learn" Width="280">
<tabdata:LearnTabItem/>
</TabItem>
<TabItem Header="Database" Width="280">
<tabdata:DatabaseTabItem/>
</TabItem>
<TabItem Header="Statistics" Width="299">
<tabdata:StatisticsTabItem/>
</TabItem>
</Controls:MetroAnimatedTabControl>
Code behind:
public partial class InitialWindow : MetroWindow
{
InitialWindowViewModel viewModel=new InitialWindowViewModel();
public InitialWindow()
{
InitializeComponent();
DataContext = viewModel;
}
}
}
DatabaseTabItem:
<UserControl x:Class="Test.View.TabItems.DatabaseTabItem"
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:Controls="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro"
xmlns:tabData="clr-namespace:Test.View.TabItems"
Height="500" Width="900" Background="White" BorderBrush="Transparent">
<UserControl.Resources>
</UserControl.Resources>
<Grid>
<Controls:MetroAnimatedTabControl x:Name ="DatabaseTabControl" Grid.Column="0" TabStripPlacement="Left" >
<TabItem Header="Choose" Width="250" >
<tabData:ChooseFromDbTabItem/>
</TabItem>
<TabItem Header="Add" Width="250">
<tabData:AddToDbTabItem/>
</TabItem>
<TabItem Header="Remove" Width="250">
<tabData:DeleteFromDbTabItem/>
</TabItem>
</Controls:MetroAnimatedTabControl>
</Grid>
code behind:
DatabaseViewModel vm = new DatabaseViewModel();
public DatabaseTabItem()
{
InitializeComponent();
DataContext = vm;
}
}
ChooseFromDbTabItem:
<UserControl x:Class="Test.View.TabItems.ChooseFromDbTabItem"
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"
xmlns:local="clr-namespace:Test.View.TabItems"
xmlns:Controls="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro"
mc:Ignorable="d"
d:DesignHeight="500" d:DesignWidth="650" Background="White" BorderBrush="Transparent">
<Grid>
<ListBox HorizontalAlignment="Center" Height="450" VerticalAlignment="Top" Width="250"
x:Name="LbxMenu" Background="{x:Null}" BorderBrush="{x:Null}"
ItemsSource="{Binding TestListsNames}" FontFamily="Segoe UI Semilight" FontSize="18"/>
</Grid>
code behind:
public partial class ChooseFromDbTabItem : UserControl
{
public ChooseFromDbTabItem()
{
InitializeComponent();
}
}

You have to rise PropertyChanged event for the reason you change your entire collection and not a single item (if you changed a single item that was updated through the Observable).
private ObservableCollection<string> _testListsName;
public ObservableCollection<string> TestListsNames
{
get { return _testListsName; }
set
{
if (_testListsName != value)
{
_testListsName = value;
NotifyPropertyChanged("TestListsNames");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string property)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(property));
}

You are not raising the PropertyChanged event when replacing the list using the property setter. Generelly, try to make collection properties readonly to reduce the risk for these sort of errors. Instead, clear the list and repopulate it. This will make sure that the view is notified about any changes.
public class ViewModel
{
private readonly ObservableCollection<string> _testListsName;
public ObservableCollection<string> TestListsNames
{
get { return _testListsName; }
}
private void TestListNamesInitialize()
{
_testListsName.Clear();
foreach(string name in db.GetTestListNamesFromDatabase())
{
_testListsName.Add(name);
}
if (_testListsNames.Count != 0) CanLoad = true;
}
}
However, note that this will raise changed events on each item using the .Add() call. See here: Can I somehow temporarily disable WPF data binding changes?
Edit: from your updated code. It can also be seen that you do not set the DataContext on your ChooseFromDbTabItem. You need to bind the DataContext property to the view model that exposes the collection:
<TabItem Header="Choose" Width="250" >
<tabData:ChooseFromDbTabItem DataContext="{Binding}" />
</TabItem>

Related

Observable Collection not updating view inside user control [duplicate]

This question already has answers here:
Issue with DependencyProperty binding
(3 answers)
Binding to custom control inside DataTemplate for ItemsControl
(1 answer)
How to pass data from MainWindow to a User Control that's inside the MainWindow?
(1 answer)
Closed 3 years ago.
I am learning WPF for work and working on a simple Todo List application, and have run into some problems with the Observable List not updating the view.
I am using the MVVM Light framework, and have done a test subscription to the CollectionChanged event which does get fired when I add elements. I am doing multiple views, so in the off chance that I am not in the main UI thread I've added the MVVM Light's DispatcherHelper to ensure it is being invoked on the main thread. I've also tried manually re-triggering the INotifyPropertyChanged by using MVVM Light's RaisePropertyChanged function on the observable list (see the commented out code). To ensure it was not me screwing up the XAML I also changed the ListBox to a DataGrid with the same results.
Here are a list of some of the stack overflow messages I tried and tutorials I've followed trying to get this done:
Observable Collection Not Updating View
Observablecollection not updating list, when an item gets added
WPF MVVM observable collection not updating GUI
Binding to an Observable Collection
Using Mvvm Light
Todo Model Class
namespace WPFTodoList.Models
{
class TodoItem : ObservableObject
{
public String Title { get { return this._title; } set
{
Set(() => this.Title, ref this._title, value);
}
}
public String Description { get { return this._description; } set
{
Set(() => this.Description, ref this._description, value);
}
}
public int Priority { get { return this._priority; } set
{
Set(() => this.Priority, ref this._priority, value);
}
}
public bool Done { get { return this._done; } set
{
Set(() => this._done, ref this._done, value);
}
}
private String _title;
private String _description;
private int _priority;
private bool _done;
}
}
View Model Class
class TodoListAppViewModel : ViewModelBase
{
public ObservableCollection<TodoItem> Todos { get; private set; }
public RelayCommand AddTodoItemCommand { get{ return this._addTodoItemCommand ?? this._BuildAddTodoItemCommand(); } }
private RelayCommand _addTodoItemCommand;
private NavigationService _navService;
private TodoService _todoService;
private IDisposable _addTodoSubscription;
public TodoListAppViewModel(NavigationService nav, TodoService todo)
{
this._navService = nav;
this._todoService = todo;
this.InitViewModel();
}
public TodoListAppViewModel()
{
this._navService = NavigationService.GetInstance();
this._todoService = TodoService.GetInstance();
this.InitViewModel();
}
private void InitViewModel()
{
this.Todos = new ObservableCollection<TodoItem>();
this.Todos.CollectionChanged += this.CollectionChanged;
this._addTodoSubscription = this._todoService.AddTodoItem.Subscribe((value) =>
{
/*this.Todos.Add(value);
RaisePropertyChanged(() => this.Todos);*/
DispatcherHelper.CheckBeginInvokeOnUI(() => this.Todos.Add(value));
});
}
private RelayCommand _BuildAddTodoItemCommand()
{
this._addTodoItemCommand = new RelayCommand( () => this._navService.NavigateTo("addEdit"));
return this._addTodoItemCommand;
}
private void CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
Console.WriteLine(e.Action.ToString());
}
~TodoListAppViewModel()
{
this._addTodoSubscription.Dispose();
}
}
}
View XAML
<UserControl x:Class="WPFTodoList.Views.TodoListAppView"
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"
xmlns:local="clr-namespace:WPFTodoList.Views"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<UserControl.Resources>
<DataTemplate x:Key="TodoItemTemplate">
<Label Content="{Binding Title}"/>
</DataTemplate>
</UserControl.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="8*" MaxHeight="180px"/>
<RowDefinition Height="16*"/>
</Grid.RowDefinitions>
<StackPanel Margin="24,-20,0,0" VerticalAlignment="Center" HorizontalAlignment="Left" Panel.ZIndex="5">
<Label Content="Your" Foreground="White" FontSize="16" />
<Label Content="Todo List" Foreground="White" FontSize="24" Margin="0,-15,0,0" />
</StackPanel>
<Rectangle HorizontalAlignment="Stretch" VerticalAlignment="Stretch" RenderTransformOrigin="0.5,0.5">
<Rectangle.Fill>
<RadialGradientBrush GradientOrigin="0.2,0.1" RadiusX="1" RadiusY="1" SpreadMethod="Reflect" MappingMode="RelativeToBoundingBox" Center="0.1,0.1">
<GradientStop Color="#FF5B447C" Offset="0.329"/>
<GradientStop Color="#FF1D1F5A" Offset="1"/>
</RadialGradientBrush>
</Rectangle.Fill>
</Rectangle>
<Rectangle Fill="#3FFFFFFF" VerticalAlignment="Bottom" Height="40" Panel.ZIndex="5"/>
<StackPanel Panel.ZIndex="10" Height="40" HorizontalAlignment="Right" VerticalAlignment="Bottom" Orientation="Horizontal">
<Button Background="Transparent" BorderBrush="Transparent" HorizontalAlignment="Right" Command="{Binding AddTodoItemCommand}" BorderThickness="0,0,0,0" SnapsToDevicePixels="True" >
<Button.ToolTip>
<Label Content="Add A Todo Item"/>
</Button.ToolTip>
<Image Source="../Resources/add.png" HorizontalAlignment="Right" />
</Button>
</StackPanel>
<ListBox Grid.Row="1" ItemsSource="{Binding Todos}" ItemTemplate="{DynamicResource TodoItemTemplate}"/>
</Grid>
</UserControl>
View Code Back
public partial class TodoListAppView : UserControl
{
public TodoListAppView()
{
InitializeComponent();
TodoListAppViewModel vm = new TodoListAppViewModel();
this.DataContext = vm;
}
}
To simulate the todo without another 4-6 files I used a RX.net subject to relay the todo item from the other view to the list view (I can post code if requested).
As for how the window displays the views here is the root xaml
<Window x:Class="WPFTodoList.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:WPFTodoList"
mc:Ignorable="d"
xmlns:views="clr-namespace:WPFTodoList.Views"
xmlns:viewModels="clr-namespace:WPFTodoList.ViewModels"
Title="MainWindow" Height="600" Width="300">
<Window.Resources>
<DataTemplate x:Name="AddEditPage" DataType="{x:Type viewModels:AddEditTodoViewModel}">
<views:AddEditTodoView DataContext="{Binding}"/>
</DataTemplate>
<DataTemplate x:Name="TodoListApp" DataType="{x:Type viewModels:TodoListAppViewModel}">
<views:TodoListAppView DataContext="{Binding}"/>
</DataTemplate>
</Window.Resources>
<Grid>
<ContentControl Content="{Binding ActivePage}"/>
</Grid>
</Window>
ActivePage is then bound to an instance of TodoListAppViewModel
The expected behavior is when the subscription to the TodoService.AddTodoItem subscription is fired, the provided instance of a TodoListItem passed to the lambda should be added to the observable Todos list. The list in turn should update the view. Right now I am seeing the CollectionChanged event being fired inside of TodoListAppViewModel, however the view does not update.

Closing an Open Window Using MVVM Pattern, Produces System.NullReferenceException error

I'm trying to learn MVVM pattern using WPF C#. And I'm running into an error when trying to close an opened window after saving information to an sqlite database. When the command to save a new contact is raised, I am getting an error on HasAddedContact(this, new EventArgs());
Error: System.NullReferenceException: 'Object reference not set to an instance of an object.'
My ViewModel:
public class NewContactViewModel : BaseViewModel
{
private ContactViewModel _contact;
public ContactViewModel Contact
{
get { return _contact; }
set { SetValue(ref _contact, value); }
}
public SaveNewContactCommand SaveNewContactCommand { get; set; }
public event EventHandler HasAddedContact;
public NewContactViewModel()
{
SaveNewContactCommand = new SaveNewContactCommand(this);
_contact = new ContactViewModel();
}
public void SaveNewContact()
{
var newContact = new Contact()
{
Name = Contact.Name,
Email = Contact.Email,
Phone = Contact.Phone
};
DatabaseConnection.Insert(newContact);
HasAddedContact(this, new EventArgs());
}
}
SaveNewContactCommand:
public class SaveNewContactCommand : ICommand
{
public NewContactViewModel VM { get; set; }
public SaveNewContactCommand(NewContactViewModel vm)
{
VM = vm;
}
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
VM.SaveNewContact();
}
}
NewContactWindow.Xaml.Cs code behind:
public partial class NewContactWindow : Window
{
NewContactViewModel _viewModel;
public NewContactWindow()
{
InitializeComponent();
_viewModel = new NewContactViewModel();
DataContext = _viewModel;
_viewModel.HasAddedContact += Vm_ContactAdded;
}
private void Vm_ContactAdded(object sender, EventArgs e)
{
this.Close();
}
}
Adding additional code where I call the new window:
public class ContactsViewModel
{
public ObservableCollection<IContact> Contacts { get; set; } = new ObservableCollection<IContact>();
public NewContactCommand NewContactCommand { get; set; }
public ContactsViewModel()
{
NewContactCommand = new NewContactCommand(this);
GetContacts();
}
public void GetContacts()
{
using(var conn = new SQLite.SQLiteConnection(DatabaseConnection.dbFile))
{
conn.CreateTable<Contact>();
var contacts = conn.Table<Contact>().ToList();
Contacts.Clear();
foreach (var contact in contacts)
{
Contacts.Add(contact);
}
}
}
public void CreateNewContact()
{
var newContactWindow = new NewContactWindow();
newContactWindow.ShowDialog();
GetContacts();
}
}
ContactsWindow.Xaml
<Window x:Class="Contacts_App.View.ContactsWindow"
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:Contacts_App.View"
xmlns:vm="clr-namespace:Contacts_App.ViewModel"
mc:Ignorable="d"
Title="Contacts Window" Height="320" Width="400">
<Window.Resources>
<vm:ContactsViewModel x:Key="vm"/>
</Window.Resources>
<StackPanel Margin="10">
<Button
Content="New Contact"
Command="{Binding NewContactCommand}"/>
<TextBox Margin="0,5,0,5"/>
<ListView
Height="200"
Margin="0,5,0,0"
ItemsSource="{Binding Contacts}">
<ListView.ItemTemplate>
<DataTemplate>
<Label Content="{Binding Name}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackPanel>
</Window>
NewContactWindow.Xaml
<Window x:Class="Contacts_App.View.NewContactWindow"
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:Contacts_App.View"
xmlns:vm="clr-namespace:Contacts_App.ViewModel"
mc:Ignorable="d"
Title="New Contact Window" Height="250" Width="350">
<Window.Resources>
<vm:NewContactViewModel x:Key="vm"/>
</Window.Resources>
<Grid>
<StackPanel
Margin="10">
<Label Content="Name" />
<TextBox
Text="{Binding Source={StaticResource vm}, Path=Contact.Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
Margin="0,0,0,5"/>
<Label Content="Email" />
<TextBox
Text="{Binding Source={StaticResource vm}, Path=Contact.Email, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
Margin="0,0,0,5"/>
<Label Content="Phone Number" />
<TextBox
Text="{Binding Source={StaticResource vm}, Path=Contact.Phone, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
Margin="0,0,0,5"/>
<Button
Content="Save"
Command="{Binding Source={StaticResource vm}, Path=SaveNewContactCommand}"/>
</StackPanel>
</Grid>
</Window>
You're creating NewContactWindow's viewmodel in the constructor, correctly assigning it to DataContext, and correctly adding a handler to that event. Unfortunately, you also create a second instance of the same viewmodel in resources, and you manually set the Source property of all the bindings to use the one in the resources, which doesn't have the event handler.
Window.DataContext, which you set in the constructor, is the default Source for any binding in the Window XAML. Just let it do its thing. I also removed all the redundant Mode=TwoWay things from the Bindings to TextBox.Text, since that property is defined so that all bindings on it will be TwoWay by default. I don't think UpdateSourceTrigger=PropertyChanged is doing anything necessary or helpful either: That causes the Binding to update your viewmodel property every time a key is pressed, instead of just when the TextBox loses focus. But I don't think you're doing anything with the properties where that would matter; there's no validation or anything. But TextBox.Text is one of the very few places where that's actually used, so I left it in.
You should remove the analagous viewmodel resource in your other window. It's not doing any harm, but it's useless at best. At worst, it's an attractive nuisance. Kill it with fire and bury the ashes under a lonely crossroads at midnight.
<Window x:Class="Contacts_App.View.NewContactWindow"
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:Contacts_App.View"
xmlns:vm="clr-namespace:Contacts_App.ViewModel"
mc:Ignorable="d"
Title="New Contact Window" Height="250" Width="350">
<Grid>
<StackPanel
Margin="10">
<Label Content="Name" />
<TextBox
Text="{Binding Contact.Name, UpdateSourceTrigger=PropertyChanged}"
Margin="0,0,0,5"/>
<Label Content="Email" />
<TextBox
Text="{Binding Contact.Email, UpdateSourceTrigger=PropertyChanged}"
Margin="0,0,0,5"/>
<Label Content="Phone Number" />
<TextBox
Text="{Binding Contact.Phone, UpdateSourceTrigger=PropertyChanged}"
Margin="0,0,0,5"/>
<Button
Content="Save"
Command="{Binding SaveNewContactCommand}"/>
</StackPanel>
</Grid>
</Window>

Get the selected tab in the view model (wpf)

I have one main view which has a tab control. When a tab is selected, it calls the appropriate view to display. I have a function in view model which has to know which tab was selected to preform an operation. How do I achieve this? How will the view model know which tab is selected?
Quite simply:
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication2"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<local:TestViewModel x:Key="MainViewModel"/>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="50"/>
</Grid.RowDefinitions>
<TabControl DataContext="{StaticResource MainViewModel}"
SelectedIndex="{Binding Selected}"
Grid.Row="0"
x:Name="TestTabs">
<TabItem Header="Section 1"/>
<TabItem Header="Section 2"/>
<TabItem Header="Section 3"/>
</TabControl>
<Button Content="Check
Selected Index"
Grid.Row="1"
x:Name="TestButton"
Click="TestButton_OnClick"/>
</Grid>
</Window>
The model is defined here, declaratively, as a data context. The selectedindex property is bound to the model so any time it changes, the propery it is mapped to on the view model will also change
class TestViewModel : INotifyPropertyChanged
{
private int _selected;
public int Selected
{
get { return _selected; }
set
{
_selected = value;
OnPropertyChanged("Selected");
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string property)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
}
This implements INotifyPropertyChanged so the view will register with it. In the handler here, I output the value of Selected to show the as you change them.
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void TestButton_OnClick(object sender, RoutedEventArgs e)
{
var vm = TestTabs.DataContext as TestViewModel;
MessageBox.Show(string.Format("You selected tab {0}", vm.Selected));
}
}
This gets the viewmodel and then shows us that the properties were in fact updated.
In View, you put SelectedIndex property on TabControl:
xmlns:cal="http://www.caliburnproject.org"
<TabControl cal:Message.Attach="[SelectionChanged] = [OnTabSelectionChanged()]"
SelectedIndex="{Binding SelectedIndexTab}">
<TabItem Header="Tab 1"/>
<TabItem Header="Tab 2"/>
</TabControl>
In ViewModel, you declare a public property name SelectedIndexTab and OnTabSelectionChanged() method to operate.
public int SelectedIndexTab { get; set; }
In this example, I use Caliburn to catch SelectionChange event of TabControl.
You can use the SelectionChanged event provided by the Selector base class. The SelectionChangedEventArgs will contain the newly selected (and deselected) items. Alternatively, you can bind the SelectedItem of the Selector Base class to a property in your ViewModel, and then perform some logic in the setter.
Generally though, it's considered a violation of MVVM to pass view-specific objects to your ViewModels - it tightly couples the UI framework (WPF in this case) to the more generic ViewModel logic. A better route is to put event handlers in your UI code-behind which in turn act on the view-model appropriately, but without passing View objects as parameters.
Here is a simple example.
You should be binding the ItemsSource of the Tab to your ObservableCollection, and that should hold models with information about the tabs that should be created.
Here are the VM and the model which represents a tab page:
public class ViewModel
{
public ObservableCollection<TabItem> Tabs { get; set; }
public ViewModel()
{
Tabs = new ObservableCollection<TabItem>();
Tabs.Add(new TabItem { Header = "One", Content = "One's content" });
Tabs.Add(new TabItem { Header = "Two", Content = "Two's content" });
}
}
public class TabItem
{
public string Header { get; set; }
public string Content { get; set; }
}
Here`s the View and VM binding
<Window x:Class="WpfApplication12.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">
<Window.DataContext>
<ViewModel
xmlns="clr-namespace:WpfApplication12" />
</Window.DataContext>
<TabControl
ItemsSource="{Binding Tabs}">
<TabControl.ItemTemplate>
<!-- this is the header template-->
<DataTemplate>
<TextBlock
Text="{Binding Header}" />
</DataTemplate>
</TabControl.ItemTemplate>
<TabControl.ContentTemplate>
<!-- this is the body of the TabItem template-->
<DataTemplate>
<----- usercontrol namespace goes here--->
</DataTemplate>
</TabControl.ContentTemplate>
Source:link

c# DataBinding in User control Win8

I've a ObservableCollection's list that receives data from the database, and i put this data in my grid, by data binding.
So, i've a user control that appears when i click in a item of this grid. I want that a text box of my user control, show the selected item of my grid.
I've tried this using data binding, but the textbox not shows the selected item.. is it possible ?
grid code:
<FlexGrid:C1FlexGrid
x:Name="grid" ItemsSource="{Binding list3, Mode=TwoWay}"
AutoGenerateColumns="False"
HorizontalAlignment="Left" Height="431" Margin="10,147,0,0" VerticalAlignment="Top" Width="1152" SelectionMode="Row" KeepCurrentVisible="True" Tapped="grid_Tapped" >
<FlexGrid:C1FlexGrid.DataContext>
<local:Controller/>
</FlexGrid:C1FlexGrid.DataContext>
<FlexGrid:C1FlexGrid.Columns>
<FlexGrid:Column Binding="{Binding describe}" Header="Describes" Width="800" />
<FlexGrid:Column Binding="{Binding describeNote}" Header="Describes Notes" Width="300" />
</FlexGrid:C1FlexGrid.Columns>
</FlexGrid:C1FlexGrid>
User Control code:
<UserControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Binding"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:FlexGrid="using:C1.Xaml.FlexGrid"
x:Class="Binding.popNotas"
mc:Ignorable="d" Height="281.925" Width="656.03">
<Grid>
<TextBox x:Name="txt2" Text="{Binding SelectedItem.describe, ElementName=grid, Mode=TwoWay}" Height="38" Margin="140,5,141,0" TextWrapping="Wrap" VerticalAlignment="Top">
</TextBox>
</Grid>
cs code
public class Controller : Common.BindableBase
{
//DAOS
public TesteDao dao { get; set; }
private ObservableCollection<ClPasso> _list3 = new ObservableCollection<ClPasso>();
public ObservableCollection<ClPasso> list3
{
get { return _list3; }
set { this.SetProperty(ref this._list3, value); }
}
public Controller()
{
OnNavigatedTo();
}
protected async void OnNavigatedTo()
{
await InitializeDatabase();
list3 = await createlist3();
}
private async Task InitializeDatabase()
{
string datbasePath = Windows.Storage.ApplicationData.Current.LocalFolder.Path + "\\bd_example.db";
DataBase database = new DataBase (datbasePath);
await database.initialize();
dao = new TesteDao(database);
}
public async Task<ObservableCollection<ClPasso>> createlist3()
{
return await dao.joinListAsync(123, "924be4cc-16db-40c2-b342-d6c1fccbec86");
}
}
Help!
Thanks!!!
i've solved my question..
So, i created a DependencyProperty on code behind of my User Control, named selection, and i put this in Text of my text box.. after, when i will using my user control, in my main page, i passed the value in for porperty..
Like this:
User Control
public sealed partial class UCNotes : UserControl
{
public string selection
{
get { return (string)GetValue(selectionProperty); }
set { SetValue(selectionProperty, value); }
}
public static readonly DependencyProperty selecionadoProperty =
DependencyProperty.Register("selection", typeof(string), typeof(UCNotes), new PropertyMetadata(null));
User Control XAML
<UserControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Test"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:FlexGrid="using:C1.Xaml.FlexGrid"
x:Class="Fiscalizacao.UCNotes"
mc:Ignorable="d"
d:DesignHeight="327.068" Width="799.248">
<Grid Margin="10,0,10,10" Background="#FFB2B2B2" Height="303" VerticalAlignment="Bottom">
<TextBox x:Name="txtSelection" Text="{Binding selection}" Height="38" Margin="153,75,153,0" TextWrapping="Wrap" VerticalAlignment="Top" BorderBrush="Black"/>
Main Page XAML
<FlexGrid:C1FlexGrid
x:Name="questionsGrid"
HorizontalAlignment="Left" Height="417" Margin="31,181,0,0" VerticalAlignment="Top" Width="1306"
AutoGenerateColumns="False" KeepCurrentVisible="True"
SelectionMode="Row" ItemsSource="{Binding list, Mode=TwoWay}">
<FlexGrid:C1FlexGrid.Columns>
<FlexGrid:Column Binding="{Binding describes}" Header="Descrição" Width="900" />
<FlexGrid:Column Binding="{Binding descibesNotes}" Header="Nota" Width="*" />
</FlexGrid:C1FlexGrid.Columns>
</FlexGrid:C1FlexGrid>
<Popup x:Name="popNotes" IsLightDismissEnabled="True" IsOpen="False" HorizontalAlignment="Center" VerticalAlignment="Center" Grid.Row="1" Grid.Column="1" Margin="0,0,700,300" >
<local:UCNotes selection="{Binding SelectedItem.describes, ElementName=questionsGrid" />
</Popup>

WPF data templates

I'm getting started with WPF and trying to get my head around connecting data to the UI. I've managed to connect to a class without any issues, but what I really want to do is connect to a property of the main window.
Here's the XAML:
<Window x:Class="test3.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:custom="clr-namespace:test3"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<CollectionViewSource
Source="{Binding Source={x:Static Application.Current}, Path=Platforms}"
x:Key="platforms"/>
<DataTemplate DataType="{x:Type custom:Platform}">
<StackPanel>
<CheckBox IsChecked="{Binding Path=Selected}"/>
<TextBlock Text="{Binding Path=Name}"/>
</StackPanel>
</DataTemplate>
</Window.Resources>
<Grid>
<ListBox ItemsSource="{Binding Source={StaticResource platforms}}"/>
</Grid>
Here's the code for the main window:
public partial class MainWindow : Window
{
ObservableCollection<Platform> m_platforms;
public MainWindow()
{
m_platforms = new ObservableCollection<Platform>();
m_platforms.Add(new Platform("PC"));
InitializeComponent();
}
public ObservableCollection<Platform> Platforms
{
get { return m_platforms; }
set { m_platforms = value; }
}
}
Here's the Platform class:
public class Platform
{
private string m_name;
private bool m_selected;
public Platform(string name)
{
m_name = name;
m_selected = false;
}
public string Name
{
get { return m_name; }
set { m_name = value; }
}
public bool Selected
{
get { return m_selected; }
set { m_selected = value; }
}
}
This all compiles and runs fine but the list box displays with nothing in it. If I put a breakpoint on the get method of Platforms, it doesn't get called. I don't understand as Platforms is what the XAML should be connecting to!
Your code looks ok apart from the fact that the Binding on Source on CollectionViewSource is not correct. You probably meant this:
<CollectionViewSource
Source="{Binding Source={x:Static Application.Current}, Path=MainWindow.Platforms}"
x:Key="platforms"/>
Without this change the Binding actually looked for property Platforms on Application instance.
I would suggest you add the platforms not to the MainWindow but rather set it as the MainWindow's DataContext (wrapped inside a ViewModel).
That way you can very easily bind against it (the binding code would look like ItemsSource={Binding Path=Platforms}).
This is part of WPFs design, that every form should have a explicit DataContext it binds to.
A somewhat more appropriate solution is to give your window a name. A nice convention is _this.
<Window x:Name="_this" x:Class="test3.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:custom="clr-namespace:test3"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<CollectionViewSource
Source="{Binding ElementName=_this, Path=Platforms}"
x:Key="platforms"/>
<DataTemplate DataType="{x:Type custom:Platform}">
<StackPanel>
<CheckBox IsChecked="{Binding Path=Selected}"/>
<TextBlock Text="{Binding Path=Name}"/>
</StackPanel>
</DataTemplate>
</Window.Resources>
<Grid>
<ListBox ItemsSource="{Binding Source={StaticResource platforms}}"/>
</Grid>
Here's my updated code, the XAML:
<Window x:Name="_this"
x:Class="test3.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:custom="clr-namespace:test3"
Title="MainWindow" Height="190" Width="177">
<Window.Resources>
<CollectionViewSource
Source="{Binding ElementName=_this, Path=Platforms}"
x:Key="platforms"/>
<DataTemplate x:Key="platformTemplate" DataType="{x:Type custom:Platform}">
<StackPanel Orientation="Horizontal">
<CheckBox Margin="1" IsChecked="{Binding Path=Selected}"/>
<TextBlock Margin="1" Text="{Binding Path=Name}"/>
</StackPanel>
</DataTemplate>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition Height="23" />
<RowDefinition Height="23" />
</Grid.RowDefinitions>
<ListBox Grid.Row="0"
ItemsSource="{Binding Source={StaticResource platforms}}"
ItemTemplate="{StaticResource platformTemplate}"/>
<Button Click="OnBuild" Grid.Row="1">Build...</Button>
<Button Click="OnTogglePC" Grid.Row="2">Toggle PC</Button>
</Grid>
</Window>
The code behind the XAML:
public partial class MainWindow : Window
{
ObservableCollection<Platform> m_platforms;
public MainWindow()
{
m_platforms = new ObservableCollection<Platform>();
m_platforms.Add(new Platform("PC"));
m_platforms.Add(new Platform("PS3"));
m_platforms.Add(new Platform("Xbox 360"));
InitializeComponent();
}
public ObservableCollection<Platform> Platforms
{
get { return m_platforms; }
set { m_platforms = value; }
}
private void OnBuild(object sender, RoutedEventArgs e)
{
string text = "";
foreach (Platform platform in m_platforms)
{
if (platform.Selected)
{
text += platform.Name + " ";
}
}
if (text == "")
{
text = "none";
}
MessageBox.Show(text, "WPF TEST");
}
private void OnTogglePC(object sender, RoutedEventArgs e)
{
m_platforms[0].Selected = !m_platforms[0].Selected;
}
}
...and finally the Platform code, enhanced to finish off the two way interaction:
public class Platform : INotifyPropertyChanged
{
private string m_name;
private bool m_selected;
public Platform(string name)
{
m_name = name;
m_selected = false;
}
public string Name
{
get { return m_name; }
set
{
m_name = value;
OnPropertyChanged("Name");
}
}
public bool Selected
{
get { return m_selected; }
set
{
m_selected = value;
OnPropertyChanged("Selected");
}
}
private void OnPropertyChanged(string name)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
Using DataContext, it gets even easier!
<Window x:Class="test5.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:custom="clr-namespace:test5"
Title="MainWindow" Height="190" Width="177">
<Window.Resources>
<CollectionViewSource
Source="{Binding Path=.}"
x:Key="platforms"/>
<DataTemplate x:Key="platformTemplate" DataType="{x:Type custom:Platform}">
<StackPanel Orientation="Horizontal">
<CheckBox Margin="1" IsChecked="{Binding Path=Selected}"/>
<TextBlock Margin="1" Text="{Binding Path=Name}"/>
</StackPanel>
</DataTemplate>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition Height="23" />
<RowDefinition Height="23" />
</Grid.RowDefinitions>
<ListBox Grid.Row="0"
ItemsSource="{Binding Source={StaticResource platforms}}"
ItemTemplate="{StaticResource platformTemplate}"/>
<Button Click="OnBuild" Grid.Row="1">Build...</Button>
<Button Click="OnTogglePC" Grid.Row="2">Toggle PC</Button>
</Grid>
</Window>
Here's the code behind this:
private ObservableCollection<Platform> m_platforms;
public MainWindow()
{
InitializeComponent();
m_platforms = new ObservableCollection<Platform>();
m_platforms.Add(new Platform("PC"));
m_platforms.Add(new Platform("PS3"));
m_platforms.Add(new Platform("Xbox 360"));
DataContext = m_platforms;
}
public void OnBuild(object sender, RoutedEventArgs e)
{
string text = "";
foreach (Platform platform in m_platforms)
{
if (platform.Selected)
{
text += platform.Name + " ";
}
}
if (text == "")
{
text = "none";
}
MessageBox.Show(text, "WPF TEST");
}
public void OnTogglePC(object sender, RoutedEventArgs e)
{
m_platforms[0].Selected = !m_platforms[0].Selected;
}
Note that I've dropped the need to declare Platforms as a property of the main window, instead I assign it to the DataContext, and the XAML source becomes, simply, "."

Categories