SplitView's Pane Content Template with MVVM - c#

I need some help wrapping my brain around the concepts of MVVM. I must say that it's been hard to learn it so far becasue some information on the internet contradict each other. So if anyone has a reliable source of information/tutorial which can get me somewhere, I'd really appreciate it.
However, for now, I need help figuruing out how I can close the SplitView Pane in UWP app with the help of MVVM from the Content of the Pane. I have a ShellView whcih hosts the SplitView and its Pane hosts a ContentPresenter whose content can be dynamically changed to one of two Templates. The Bindng properties are within the ViewModel and so is the IsSubscriptionsPaneOpen property.
ShellView.xaml (Page):
<SplitView
Name="sv"
DisplayMode="Overlay"
OpenPaneLength="280"
IsPaneOpen="{Binding IsSubscriptionsPaneOpen, Mode=TwoWay, UpdateSourceTrigger=Default}">
<SplitView.Pane>
<ContentPresenter
Content="{Binding PaneContent, Mode=OneWay, UpdateSourceTrigger=Default}"
ContentTransitions="{StaticResource NavigationTransitions}"/>
</SplitView.Pane>
<Grid>
<Frame
x:Name="RootFrame"
ContentTransitions="{StaticResource NavigationTransitions}"/>
</Grid>
</SplitView>
Then comes one of the Templates' View which needs to be instantiated in the PaneContent property. I do it within the ShellViewModel as below:
private SubscriptionsView SubsPaneView { get; set; }
if (SubsPaneView == null) SubsPaneView = new SubscriptionsView();
PaneContent = SubsPaneView;
SubscriptionView.xaml (UserControl):
<UserControl.Resources>
<ViewModels:SubscriptionsViewModel x:Key="SubsVM"/>
<DataTemplate x:Key="UserSubscriptionsDataTemplate"
x:DataType="model:SubscriptionsItem">
<UserControl>
<Grid
Name="rootPanel">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Grid.Background>
<ImageBrush
ImageSource="{Binding ChannelCoverUrl, Mode=OneWay, UpdateSourceTrigger=Default}"
Opacity="0.4"/>
</Grid.Background>
<Ellipse
Name="imageBorder"
Grid.Column="0"
Height="44"
Width="44"
Stroke="{StaticResource SystemControlBackgroundAccentBrush}"
StrokeThickness="1"
VerticalAlignment="Center">
<Ellipse.Fill>
<ImageBrush>
<ImageBrush.ImageSource>
<BitmapImage
UriSource="{Binding ImageUrl, Mode=OneWay}"/>
</ImageBrush.ImageSource>
</ImageBrush>
</Ellipse.Fill>
</Ellipse>
<TextBlock
Name="title"
Grid.Column="1"
Style="{StaticResource BodyTextBlockStyle}"
Text="{Binding Title, Mode=OneWay, UpdateSourceTrigger=Default}"
MaxLines="2"
TextTrimming="CharacterEllipsis"
Margin="4,0"
VerticalAlignment="Center"
ToolTipService.ToolTip="{Binding Title, Mode=OneWay}"/>
<Border
Name="newContent"
Grid.Column="2"
Background="{StaticResource SystemControlBackgroundAccentBrush}"
CornerRadius="100"
Height="36"
Width="36"
VerticalAlignment="Center"
Visibility="{Binding NewItemCount, Mode=OneWay, UpdateSourceTrigger=Default, Converter={StaticResource NumberToVisibleConverter}}">
<ToolTipService.ToolTip>
<TextBlock>
<Run Text="Updates:"/>
<Run Text="{Binding NewItemCount, Mode=OneWay, UpdateSourceTrigger=Default}"/>
</TextBlock>
</ToolTipService.ToolTip>
<TextBlock
Text="{Binding NewItemCount, Mode=OneWay, UpdateSourceTrigger=Default}"
FontSize="12"
VerticalAlignment="Center"
TextAlignment="Center"/>
</Border>
<AppBarButton
Name="subsRemoveBtn"
Grid.Column="3"
Height="40"
Width="40"
Style="{StaticResource SquareAppBarButtonStyle}"
Command="{Binding OpenUnsubscribeFlyout, Mode=OneWay, UpdateSourceTrigger=Default}"
VerticalAlignment="Center">
<AppBarButton.Icon>
<FontIcon
Glyph=""
Margin="0,-4,0,0"/>
</AppBarButton.Icon>
<FlyoutBase.AttachedFlyout>
<Flyout helpers:FlyoutHelper.IsOpen="{Binding IsFlyoutOpen, Mode=TwoWay, UpdateSourceTrigger=Default}"
helpers:FlyoutHelper.Parent="{Binding ElementName=subsRemoveBtn}">
<Button
Content="Unsubscribe"
Command="{Binding RemoveSubscription, Mode=OneWay, UpdateSourceTrigger=Default}"
CommandParameter="{Binding ID, Mode=OneWay, UpdateSourceTrigger=Default}"/>
</Flyout>
</FlyoutBase.AttachedFlyout>
<ToolTipService.ToolTip>
<TextBlock
TextWrapping="Wrap">
<Run Text="Unsubscribe"/>
<Run Text="{Binding Title, Mode=OneWay, UpdateSourceTrigger=Default}"/>
</TextBlock>
</ToolTipService.ToolTip>
</AppBarButton>
</Grid>
</UserControl>
</DataTemplate>
</UserControl.Resources>
<ListView
Name="subscriptionsList"
Grid.Row="1"
helpers:ItemClickCommand.Command="{Binding ViewChannelCommand}"
ScrollViewer.VerticalScrollBarVisibility="Hidden"
ItemTemplate="{StaticResource UserSubscriptionsDataTemplate}"
ItemsSource="{Binding SubscriptionsList, Mode=OneWay, UpdateSourceTrigger=Default}"
SelectedItem="{Binding SelectedSubscription, Mode=TwoWay, UpdateSourceTrigger=Default}"/>
At first I was closing the Pane through a readonly instance of ShellViewModel but I dont think it's purely MVVM and that is why I am looking at how to make it purely MVVM. The goal is to use the Click command of subscriptionsList to close the Pane.
public CustomICommand<SubscriptionsItem> ViewChannelCommand { get; private set; }
ViewChannelCommand = new CustomICommand<SubscriptionsItem>(ViewSubscriptionChannel, CanViewSubscriptionChannel);
private void ViewSubscriptionChannel(SubscriptionsItem channel)
{
CommandsService.ViewUserChannelForChannelID(channel.ChannelID, false);
//ShellViewModel.Instance?.IsSubscriptionsPaneOpen = false;
}
Now I don't see a way of closing the Pane through ItemTemplate of the ListView. I believe it maybe possible through Dependency Injection becasue I am using the same thing for closing the Flyouts already but I dont know how I implement it here becasue there is no documentation available. Can anyone help?
Edit:
I am using below class for ListView itemclick through MVVM pattern.
public static class ItemClickCommand
{
public static readonly DependencyProperty CommandProperty =
DependencyProperty.RegisterAttached("Command", typeof(ICommand),
typeof(ItemClickCommand), new PropertyMetadata(null, OnCommandPropertyChanged));
public static void SetCommand(DependencyObject d, ICommand value)
{
d.SetValue(CommandProperty, value);
}
public static ICommand GetCommand(DependencyObject d)
{
return (ICommand)d.GetValue(CommandProperty);
}
private static void OnCommandPropertyChanged(DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
var control = d as ListViewBase;
if (control != null)
control.ItemClick += OnItemClick;
}
private static void OnItemClick(object sender, ItemClickEventArgs e)
{
var control = sender as ListViewBase;
var command = GetCommand(control);
if (command != null && command.CanExecute(e.ClickedItem))
command.Execute(e.ClickedItem);
}
}

The reasonable thing to do here is to add another dependency property in the ItemClickCommand class above:
...
public static readonly DependencyProperty IsPanelOpenCommandProperty =
DependencyProperty.RegisterAttached("IsPanelOpenCommand", typeof(ICommand),
typeof(ItemClickCommand), null);
public static void SetIsPaneOpenCommand(DependencyObject d, ICommand value)
{
d.SetValue(IsPanelOpenCommandProperty, value);
}
public static ICommand GetIsPaneOpenCommand(DependencyObject d)
{
return (ICommand)d.GetValue(IsPanelOpenCommandProperty);
}
// in item click insert the following
var paneCommand = GetIsPaneOpenCommand(control);
if (paneCommand != null)
paneCommand.Execute();
....

Related

Could not pass values from view to viewmodel through commands

I am implementing MVVM pattern for my application. I have my Views, ViewModel, Model and Commands and Converters being implemented. Now I am not able to pass my textboxes values from my datatemplate to my ViewModel through the command binding. I am able to click on the button to attempt the update process but its not able to pass the textboxes value. Are there something i need to change on my command class?
Here is my XAML:
<DataGrid AutoGenerateColumns="False" Grid.Row="2" Grid.ColumnSpan="4" Grid.RowSpan="3" x:Name="productionLineConfigDataGrid" Margin="70,0.2,70,0" ItemsSource="{Binding listAllProductionLineConfigs}">
<DataTemplate>
<StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock FontSize="12" Text="ID: " VerticalAlignment="Center" />
<TextBlock x:Name="txtBlockLineId" FontSize="16" Foreground="MidnightBlue" Text="{Binding ProductionLineId, Mode=TwoWay}" VerticalAlignment="Center" />
</StackPanel>
<StackPanel>
<Button x:Name="btnUpdate" Content="Update" VerticalAlignment="Center" HorizontalAlignment="Right" Click="btnUpdate_Click" Command="{Binding DataContext.updateProductionLineConfigCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:production_line_config_home}}}" CommandParameter="{Binding ProductionLineConfig}"/>
</StackPanel>
</StackPanel>
</DataTemplate>
</DataGrid>
Here is the method from my ViewModel:
public ProductionLineConfig ProductionLineConfig
{
get { return productionlineconfig; }
set
{
productionlineconfig = value;
OnPropertyChanged("ProductionLineConfig");
}
}
This is the error message i am getting:
System.Windows.Data Error: 40 : BindingExpression path error: 'ProductionLineConfig' property not found on 'object' ''ProductionLineConfig' (HashCode=47309994)'. BindingExpression:Path=ProductionLineConfig; DataItem='ProductionLineConfig' (HashCode=47309994); target element is 'Button' (Name=''); target property is 'CommandParameter' (type 'Object')
I have included the image for my application here
This is the entire xaml code here and this is the entire viewmodel code here
I'm only going to take a guess at this.
Assuming ProductionLineConfig is what you are binding to for ProductionLineId in the template. Then you probably are just wanting to pass your binding source as the command parameter
CommandParameter="{Binding}"
When {Binding} is empty, it means the Binding is bound to whatever Source there is. Which is also just shorthand for...
{Binding DataContext,RelativeSource={RelativeSource Self}}.
In turn (if the stars align), then it should be your ProductionLineConfig
Based on your code source, I made a sample implementation, to achieve your requirement.
Sample VM:
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows;
namespace WpfApp5.ViewModels
{
public class ProductionLineConfigViewModel : INotifyPropertyChanged
{
public CustomCommand<ProductionLineConfig> UpdateCommand { get; }
public ProductionLineConfigViewModel()
{
PopulateProductionLineConfigs();
UpdateCommand = new CustomCommand<ProductionLineConfig>(UpdateConfig, (u) => true);
}
private ObservableCollection<ProductionLineConfig> _listAllProductionLineConfigs;
public ObservableCollection<ProductionLineConfig> listAllProductionLineConfigs
{
get { return _listAllProductionLineConfigs; }
set
{
_listAllProductionLineConfigs = value;
OnPropertyChanged();
}
}
// Call this from constructor.
private void PopulateProductionLineConfigs()
{
listAllProductionLineConfigs = new ObservableCollection<ProductionLineConfig>
{
new ProductionLineConfig
{
ProductionLineId = 1,
ProductionLineCode = "001",
ProductionLineCreatedDate = DateTime.Today.Date,
ProductionLineName = "safdsf",
ProductionLineStatus = true
},
new ProductionLineConfig
{
ProductionLineId = 1,
ProductionLineCode = "002",
ProductionLineCreatedDate = DateTime.Today.Date,
ProductionLineName = "sadfadfsdf",
ProductionLineStatus = true
}
};
}
private void UpdateConfig(ProductionLineConfig config)
{
MessageBox.Show("Line Name update: " + config.ProductionLineName);
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class ProductionLineConfig
{
public int ProductionLineId { get; set; }
public string ProductionLineCode { get; set; }
public string ProductionLineName { get; set; }
public bool ProductionLineStatus { get; set; }
public DateTime ProductionLineCreatedDate { get; set; }
}
}
Sample XAML:
<Window x:Name="Root" x:Class="WpfApp5.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:viewModels="clr-namespace:WpfApp5.ViewModels"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.DataContext>
<viewModels:ProductionLineConfigViewModel/>
</Window.DataContext>
<Grid Background="#FF006E8C">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Label Grid.ColumnSpan="4" Content="KAD ShopFloor System" HorizontalAlignment="Center" Margin="10" FontWeight="Bold" FontSize="30" FontFamily="Segoe UI" Foreground="White"/>
<Separator Grid.ColumnSpan="4" Grid.RowSpan="3" Background="White" Margin="0,-35,-0.4,39.2"/>
<DataGrid AutoGenerateColumns="False" Grid.Row="2" Grid.ColumnSpan="4" Grid.RowSpan="3" x:Name="productionLineConfigDataGrid" Margin="70,0.2,70,0"
ItemsSource="{Binding DataContext.listAllProductionLineConfigs, ElementName=Root}">
<DataGrid.Columns>
<DataGridTextColumn Header="ID" Binding="{Binding ProductionLineId, Mode=TwoWay}"/>
<DataGridTextColumn Header="Production Line Code" Binding="{Binding ProductionLineCode, Mode=TwoWay}"/>
<DataGridTextColumn Header="Production Line Name" Binding="{Binding ProductionLineName, Mode=TwoWay}"/>
<DataGridTextColumn Header="Status" Binding="{Binding ProductionLineStatus, Mode=TwoWay}"/>
<DataGridTextColumn Header="Created Date" Binding="{Binding ProductionLineCreatedDate, Mode=TwoWay}"/>
</DataGrid.Columns>
<DataGrid.RowDetailsTemplate>
<DataTemplate>
<Border BorderThickness="0" Background="BlanchedAlmond" Padding="10">
<StackPanel Orientation="Vertical" x:Name="stck">
<StackPanel Orientation="Horizontal">
<TextBlock FontSize="12" Text="ID: " VerticalAlignment="Center" />
<TextBlock x:Name="txtBlockLineId" FontSize="16" Foreground="MidnightBlue" Text="{Binding ProductionLineId, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Center" />
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock FontSize="12" Text="Line Code: " VerticalAlignment="Center" />
<TextBlock x:Name="txtBlockLineCode" FontSize="16" Foreground="MidnightBlue" Text="{Binding ProductionLineCode, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Center" />
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock FontSize="12" Text="Line Name: " VerticalAlignment="Center" />
<TextBox x:Name="txtLineName" FontSize="16" Foreground="MidnightBlue" Text="{Binding ProductionLineName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Center" />
</StackPanel>
<!--<StackPanel Orientation="Horizontal">
<TextBlock FontSize="12" Text="Status: " VerticalAlignment="Center" />
<ComboBox ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type DataGrid}},
Path=DataContext.Statusstring}" SelectedValue="{Binding ProductionLineStatus, Converter={StaticResource statusToBooleanConverter}, Mode=TwoWay}" x:Name="cbProductionLineStatus" FlowDirection="LeftToRight" FontSize="16" Foreground="MidnightBlue"
HorizontalAlignment="Stretch" VerticalAlignment="Center"/>
</StackPanel>-->
<StackPanel>
<Button x:Name="btnUpdate" Content="Update" VerticalAlignment="Center" HorizontalAlignment="Right"
Command="{Binding DataContext.UpdateCommand, ElementName=Root}"
CommandParameter="{Binding}" />
</StackPanel>
</StackPanel>
</Border>
</DataTemplate>
</DataGrid.RowDetailsTemplate>
</DataGrid>
</Grid>
</Window>
Sample output:
Key changes here,
You need to change your list to observable collection
Create a custom command that accepts an object, see this post: [UWP/MVVM]Enable/Disable Button in RadDataGrid Data Template Column that have commands bound to them upon conditions
Command Parameter should be the iterated item, can be achieve by CommandParameter={Binding}
In you two way bindings, make sure to add UpdateSourceTrigger=PropertyChanged

How to check to state of controls created dynamically using itemscontrol after naming them in the itemscontrol wpf C#

For my code, I've created multiple control of the same type (i.e. Checkbox) using itemscontrol bound to a class "MyClass". I've named the checkbox control as "checkControl". Now, as I've multiple checkbox control created in the UI, I want to check their state and differentiate among them. How should I proceed? I'm thinking of using findvisualchild & findvisualparent? But, I don't have any idea how to use it?
<ItemsControl Name="myList">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid Margin="30,80,10,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="100" />
</Grid.ColumnDefinitions>
<Border x:Name="tempBorder" BorderBrush="LightGray" BorderThickness="2,2,2,2" CornerRadius="4,4,4,4" Margin="0,-30,-60,-30"
Background="LightGray">
<StackPanel Orientation="Horizontal" Background="Transparent" Margin="0">
<StackPanel Background="White" Orientation="Horizontal">
<CheckBox x:Name="checkControl" Margin="7,7,0,0" Checked="CheckBox_Checked" Unchecked="CheckBox_Unchecked">
<WrapPanel>
<Image Source="/Images/myimage.png" Margin="0,10,0,0"></Image>
<StackPanel Orientation="Vertical" VerticalAlignment="Center">
<TextBlock Text="{Binding Disk}" FontFamily="roboto" FontSize="14"/>
<Rectangle Width="340" Height="1" Margin="0,5,5,5" Fill="Black"/>
<TextBlock>
<Run Text="Item:" FontFamily="roboto" FontSize="14"/>
<Run Text="{Binding Path=Name, StringFormat=' {0} Jr.'}" FontSize="20" Foreground="Orange"
FontWeight="DemiBold"/>
</TextBlock>
</StackPanel>
</WrapPanel>
</CheckBox>
</StackPanel>
<StackPanel Orientation="Vertical" Background="LightGray" Margin="0" HorizontalAlignment="Center" Width="765"
VerticalAlignment="Center">
<TextBlock Text="Select the Option:" Margin="15,7,0,7" FontFamily="roboto"/>
<ComboBox x:Name="comboControl" Margin="15,5,0,7" Width="750" SelectionChanged="comboControl_SelectionChanged"/>
</StackPanel>
</StackPanel>
</Border>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
For My Backend C# Code:
Class
public class MyClass
{
public string Disk { get; set; }
public string Name { get; set; }
public MyClass()
{
}
public MyClass(string album, string name)
{
this.Disk = album;
this.Name = name;
}
}
In my Xaml.cs
public ObservableCollection<MyClass> StudentDisk { get; set; }
//somecode
StudentDisk.Add(new MyClass("Disk 4 ", "John")); //For populating
//somecode
myList.ItemsSource = StudentDisk;
it is possible to differentiate checkBoxes by their DataContext, which should be unique:
void CheckBox_Checked(object sender, RoutedEventArgs e)
{
var checkbox = (CheckBox)sender;
var item = (MyClass)checkbox.DataContext;
MessageBox.Show(item.Disk + " " + item.Name);
}

UWP Reorder ListView Item loses variable value

My ListView's ItemSource consits of an ObservableCollection of GamePlayerViewModels. The CheckBox in the image sets the dealer, the arrows are a handle to move the row, the yellow button toggles a player in and out. When I move a player that is the dealer to a new position in the list, their dealer variable becomes false. I am not quite sure what to do to make that value stick when moving the item.
Before Reorder
After Reorder
public class GamePlayerViewModel : NotificationBase
{
private string _DisplayName;
private bool _Dealer;
private bool _Out;
public string DisplayName
{
get { return _DisplayName; }
set { SetProperty(ref _DisplayName, value); }
}
public bool Dealer
{
get { return _Dealer; }
set { SetProperty(ref _Dealer, value); }
}
public bool Out
{
get { return _Out; }
set { SetProperty(ref _Out, value); }
}
}
ListView xaml
<StackPanel>
<TextBlock
Text="Dealer"/>
<ListView
AllowDrop="True"
CanReorderItems="True"
ItemsSource="{x:Bind ViewModel.GamePlayerViewModels, Converter={StaticResource GamePlayerViewModelToObjectConverter}, Mode=TwoWay}">
<ListView.ItemTemplate>
<DataTemplate
x:DataType="viewModels:GamePlayerViewModel">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition
Width="*"/>
<ColumnDefinition
Width="Auto"/>
</Grid.ColumnDefinitions>
<RadioButton
Name="ChkDealer"
Content="{x:Bind DisplayName}"
GroupName="GroupDealer"
IsChecked="{x:Bind Dealer, Converter={StaticResource NullableBooleanToBooleanConverter}, Mode=TwoWay}"
IsEnabled="{x:Bind Out, Converter={StaticResource OppositeNullableBooleanToBooleanConverter}, Mode=OneWay}"
Margin="0,0,5,0"/>
<StackPanel
Grid.Column="1"
HorizontalAlignment="Right"
Orientation="Horizontal">
<Button
Background="Transparent"
HorizontalAlignment="Right"
IsEnabled="False"
Margin="0,0,5,0">
<SymbolIcon
Symbol="Sort"/>
</Button>
<Button
Click="{x:Bind GamePlayerOut, Mode=OneWay}"
HorizontalAlignment="Right"
Visibility="{x:Bind Out, Converter={StaticResource BoolToVisibilityCollapsedConverter}, Mode=OneWay}">
<SymbolIcon
Symbol="BlockContact"/>
</Button>
<Button
Click="{x:Bind GamePlayerIn, Mode=OneWay}"
HorizontalAlignment="Right"
Visibility="{x:Bind Out, Converter={StaticResource BoolToVisibilityVisibleConverter}, Mode=OneWay}">
<SymbolIcon
Symbol="AddFriend"/>
</Button>
</StackPanel>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackPanel>

My SaveCommand Button isnt working in UWP why?? I use MVVM Pattern

Ok, I've been practicing with MVVM Pattern on UWP, now I've created an object Customer EditableCustomer which is my helper property between my view and my model at my VM.
if my four properties FirstName, LastName, Email and Phone arent nulls or emptys my savecommand button should enable.
but I havent been able to raise my property changes on my EditableCustomer so that way I could Raise my SaveCommand.RaiseCanExecuteChanged().
this is my code for my view:
<UserControl
x:Class="MVVMHeirarchiesDemo.Views.AddEditCustomerView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:MVVMHeirarchiesDemo.Views"
xmlns:viewmodel="using:MVVMHeirarchiesDemo.ViewModel"
xmlns:conv="using:MVVMHeirarchiesDemo.Converters"
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">
<UserControl.DataContext>
<viewmodel:AddEditCustomerViewModel/>
</UserControl.DataContext>
<UserControl.Resources>
<conv:ValidationMessageConverter x:Key="ValidationMessageConverter"/>
</UserControl.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid x:Name="grid1"
HorizontalAlignment="Left"
Margin="10,10,0,0"
VerticalAlignment="Top">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<TextBlock Text="First Name:"
Grid.Column="0"
Grid.Row="0"
HorizontalAlignment="Left"
VerticalAlignment="Center"
Margin="3"/>
<StackPanel Orientation="Vertical"
Grid.Column="1"
Grid.Row="0">
<TextBox x:Name="firstNameTextBox"
Text="{Binding EditableCustomer.FirstName, Mode=TwoWay}"
HorizontalAlignment="Left"
VerticalAlignment="Center"
Margin="3"
Height="23"
Width="120"/>
<TextBlock x:Name="firstNameErrorMessage"
Text="{Binding EditableCustomer.ValidationMessages[FirstName], Converter={StaticResource ValidationMessageConverter}}"
Width="{Binding Width, ElementName=firstNameTextBox, Mode=OneWay}"
TextWrapping="Wrap"/>
</StackPanel>
<TextBlock Text="Last Name:"
Grid.Column="0"
Grid.Row="1"
HorizontalAlignment="Left"
VerticalAlignment="Center"
Margin="3"/>
<StackPanel Orientation="Vertical"
Grid.Column="1"
Grid.Row="1">
<TextBox x:Name="lastNameTextBox"
Text="{Binding EditableCustomer.LastName, Mode=TwoWay}"
HorizontalAlignment="Left"
VerticalAlignment="Center"
Width="{Binding Width, ElementName=firstNameTextBox, Mode=OneWay}"
Height="{Binding Height, ElementName=firstNameTextBox, Mode=OneWay}"
Margin="3"/>
<TextBlock x:Name="lastNameErrorMessage"
Text="{Binding EditableCustomer.ValidationMessages[LastName], Converter={StaticResource ValidationMessageConverter}}"
Width="{Binding Width, ElementName=firstNameTextBox, Mode=OneWay}"
TextWrapping="Wrap"/>
</StackPanel>
<TextBlock Text="Email:"
Grid.Column="0"
Grid.Row="2"
HorizontalAlignment="Left"
VerticalAlignment="Center"
Margin="3"/>
<StackPanel Orientation="Vertical"
Grid.Column="1"
Grid.Row="2">
<TextBox x:Name="emailTextBox"
Text="{Binding EditableCustomer.Email, Mode=TwoWay}"
HorizontalAlignment="Left"
VerticalAlignment="Center"
Width="{Binding Width, ElementName=firstNameTextBox, Mode=OneWay}"
Height="{Binding Height, ElementName=firstNameTextBox, Mode=OneWay}"
Margin="3"/>
<TextBlock x:Name="emailErrorMessage"
Text="{Binding EditableCustomer.ValidationMessages[Email], Converter={StaticResource ValidationMessageConverter}}"
Width="{Binding Width, ElementName=firstNameTextBox, Mode=OneWay}"
TextWrapping="Wrap"/>
</StackPanel>
<TextBlock Text="Phone:"
Grid.Column="0"
Grid.Row="3"
HorizontalAlignment="Left"
VerticalAlignment="Center"
Margin="3"/>
<StackPanel Orientation="Vertical"
Grid.Column="1"
Grid.Row="3">
<TextBox x:Name="phoneTextBox"
Text="{Binding EditableCustomer.Phone, Mode=TwoWay}"
HorizontalAlignment="Left"
VerticalAlignment="Center"
Width="{Binding Width, ElementName=firstNameTextBox, Mode=OneWay}"
Height="{Binding Height, ElementName=firstNameTextBox, Mode=OneWay}"
Margin="3"/>
<TextBlock x:Name="phoneErrorMessage"
Text="{Binding EditableCustomer.ValidationMessages[Phone], Converter={StaticResource ValidationMessageConverter}}"
Width="{Binding Width, ElementName=firstNameTextBox, Mode=OneWay}"
TextWrapping="Wrap"/>
</StackPanel>
</Grid>
<Grid Grid.Row="1">
<StackPanel Orientation="Horizontal">
<Button x:Name="saveCommandButton"
Content="Save"
Command="{Binding SaveCommand}"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Margin="25,5,0,0"
Width="75"/>
<Button x:Name="addCommandButton"
Content="Add"
Command="{Binding SaveCommand}"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Margin="25,5,0,0"
Width="{Binding Width, ElementName=saveCommandButton, Mode=OneWay}"/>
<Button x:Name="cancelCommandButton"
Content="Cancel"
Command="{Binding CancelCommand}"
HorizontalAlignment="Left"
VerticalAlignment="Center"
Margin="25,5,0,0"
Width="{Binding Width, ElementName=saveCommandButton, Mode=OneWay}"/>
</StackPanel>
</Grid>
</Grid>
As you can see at my textboxes the text property are bind to my EditableCustomer.(propertyName)
my ViewModel is this one:
public class AddEditCustomerViewModel : BindableBase
{
public AddEditCustomerViewModel()
{
CancelCommand = new MyCommand(OnCancel);
SaveCommand = new MyCommand(OnSave, CanSave);
EditableCustomer = new Customer();
}
private Customer _editableCustomer;
public Customer EditableCustomer
{
get
{
return _editableCustomer;
}
set
{
SetProperty(ref _editableCustomer, value);
SaveCommand.RaiseCanExecuteChanged();
}
}
public MyCommand CancelCommand { get; private set; }
public MyCommand SaveCommand { get; private set; }
public event Action Done = delegate { };
private void OnCancel()
{
Done();
}
private void OnSave()
{
Done();
}
private bool CanSave()
{
if (HasEmptyFields())
return false;
return true;
}
private bool HasEmptyFields()
{
return string.IsNullOrEmpty(EditableCustomer.FirstName) || string.IsNullOrEmpty(EditableCustomer.LastName)
|| string.IsNullOrEmpty(EditableCustomer.Phone) || string.IsNullOrEmpty(EditableCustomer.Email);
}
}
All i need to do is to be able to trigger the setter for my EditableCustomer property, but I've been able to do that with it.
what am i missing here??
I see my code and I think that it should be raise everytime each field has text until it becomes true once all my text boxes have text on them.
but nothing happens.
just to understand this is my BindableBase is a class where I apply my INotifyPropertyChanged.
public class BindableBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged = delegate { };
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
protected virtual void SetProperty<T>(ref T member, T val, [CallerMemberName]string propertyName = null)
{
if (object.Equals(member, val))
return;
member = val;
OnPropertyChanged(propertyName);
}
}
I hope someone can enlight me, meanwhile i'll try to keep digging on this issues.
It looks like SaveCommand.RaiseCanExecuteChanged(); is only called when you set the EditableCustomer, but when you modify the values inside that object (ie name, email, etc), nothing is notifying the UI that SaveCommand can execute.
If you're going to break up your view models like that, where you have an encapsulated class that manages the input, then it will need to notify the parent view model of changes. Your AddEditCustomerViewModel does not know when the properties have changed and cannot RaiseCanExecuteChanged() accordingly.
Update
In your case, I would recommend having the view-model route all properties that can be modified by the UI form. For example:
public class AddEditCustomerViewModel : BindableBase
{
public string FirstName
{
get { return _editableCustomer.FirstName; }
set
{
_editableCustomer.FirstName = value;
OnPropertyChanged(nameof(FirstName));
if (!HasEmptyFields())
{
SaveCommand.RaiseCanExecuteChanged();
}
}
}
}
and your XAML should bind directly to the view-model, not the model:
<TextBox Text="{Binding FirstName, Mode=TwoWay}" />

how to access DataCollection

I have a Pivot view in my WP8 app, and I'm trying to access the data collection from the view's class upon Click event "removePin".
The source of the data collection is another class called Pins.
how can I achieve that?
this is my snippet code for the XAML for that particular part
<phone:PivotItem Header="Pins">
<!-- Content Panel -->
<Grid x:Name="ContentPanel2" HorizontalAlignment="Left" Height="583" Margin="10,10,0,0" Grid.Row="1" VerticalAlignment="Top" Width="460">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="400*"/>
<ColumnDefinition Width="0*"/>
<ColumnDefinition Width="87*"/>
</Grid.ColumnDefinitions>
<ListBox x:Name="lstData2" ItemsSource="{Binding DataCollection2, Source={StaticResource PinsCollection}}"
Grid.ColumnSpan="3" Foreground="#FF1D53D0" Height="583" VerticalAlignment="Bottom">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Tap="StackPanel_Tap">
<Image Margin="8" VerticalAlignment="Top" Source="{Binding ImageUri}"
Width="100" Height="100" />
<StackPanel Height="93" Width="259" >
<TextBlock Margin="8" Width="250" TextWrapping="Wrap" VerticalAlignment="Top" HorizontalAlignment="Left" Foreground="#FF1D53D0"
Text="{Binding Pinnedname}" Height="33" RenderTransformOrigin="0.5,0.5" FontFamily="Segoe WP SemiLight" FontSize="24" FontWeight="Bold" />
<TextBlock Width="155" Margin="8,0,8,8" VerticalAlignment="Top"
HorizontalAlignment="Left" Text="{Binding Status}" Foreground="#FF1D53D0" FontFamily="Segoe WP SemiLight" />
</StackPanel>
<toolkit:ContextMenuService.ContextMenu>
<toolkit:ContextMenu>
<toolkit:MenuItem Header="Remove Pin" Click="RemovePin_Click" Tag="{Binding pinId}"/>
</toolkit:ContextMenu>
</toolkit:ContextMenuService.ContextMenu>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<!-- End of Content Panel -->
</Grid>
Create a custom command class:
public class CustomCommand : ICommand
{
Action _exec;
public CustomCommand(Action exec)
{
_exec = exec;
}
public void Execute(object parameter)
{
if (_exec != null) _exec();
}
public bool CanExecute(object parameter)
{
return true;
}
public event EventHandler CanExecuteChanged;
}
Add it to the view model for elements of pins collection (I supposed it's PinItem)
public CustomCommand RemovePinCommand
{
get { return (CustomCommand)GetValue(RemovePinCommandProperty); }
set { SetValue(RemovePinCommandProperty, value); }
}
public static readonly DependencyProperty RemovePinCommandProperty =
DependencyProperty.Register("RemovePinCommand",
typeof(CustomCommand),
typeof(PinItem),
new UIPropertyMetadata(null));
In the constructor of that class implement your logic for this command:
RemovePinCommand = new CustomCommand(() =>
{
//delete this pin from its parent collection
});
final step is to bind the command to the menu item:
<toolkit:MenuItem Header="Remove Pin" Command="{Binding RemovePinCommand}"/>

Categories

Resources