object sender is always null in RelayCommand - wpf

I am using RelayCommand to handle a button click, I need to get the sender parameter but it is always null, any idea why?
ViewModel.cs
private RelayCommand _expandClickCommand;
public ICommand ExpandClickCommand
{
get
{
if (_expandClickCommand == null)
{
_expandClickCommand = new RelayCommand(ExpandClickCommandExecute, ExpandClickCommandCanExecute);
}
return _expandClickCommand;
}
}
public void ExpandClickCommandExecute(object sender)
{
//sender is always null when i get here!
}
public bool ExpandClickCommandCanExecute(object sender)
{
return true;
}
View.xaml
<ListBox ItemsSource="{Binding Path=MyList}">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Button Grid.Column="0" Grid.Row="0" Content="Expand" Command="{Binding DataContext.ExpandClickCommand,ElementName=SprintBacklog}"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
I need to get the index of the currect ListboxItem in ExpandClickCommand

That object in all likelihood is not the sender but the CommandParameter that is passed by the control. You could bind the CommandParameter of the button to itself to immitate the sender.
CommandParameter="{Binding RelativeSource={RelativeSource Self}}"
(But that might not really help you that much, so think about what you pass in that helps you get that value.)

Related

How to bind wpf UserControl?

I am having a problem to binding viewmodel to my created usercontrol. The viewmodel doesn't reflect the value changes.
UpDown.xaml (Usercontrol xaml part)
btnUp and btnDown are used to change the text of txtNum. I don't know whether it is right?
<Grid DataContext="{Binding ElementName=btnDownRoot}">
<Grid.RowDefinitions>
<RowDefinition Height="0*"/>
<RowDefinition/>
<RowDefinition Height="0*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0*"/>
<ColumnDefinition Width="78*"/>
<ColumnDefinition Width="104*"/>
<ColumnDefinition Width="77*"/>
<ColumnDefinition Width="0*"/>
</Grid.ColumnDefinitions>
<TextBox Name="txtNum" Text="{Binding ElementName=btnDownRoot, Path=NumValue}" FontSize="20" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" BorderBrush="White" Grid.Column="2" Grid.RowSpan="2"/>
<Button Name="btnUp" Style="{StaticResource ResourceKey=btnUp}" Click="btnUp_Click" Grid.Column="3" Grid.RowSpan="2"/>
<Button Name="btnDown" Style="{StaticResource ResourceKey=btnDown}" Click="btnDown_Click" Grid.RowSpan="2" Grid.ColumnSpan="2"/>
</Grid>
UpDown.xaml.cs (Usercontrol codepart)
public string NumValue
{
get
{
return GetValue(NumValueProperty).ToString();
}
set
{
SetValue(NumValueProperty, value);
}
}
public static readonly DependencyProperty NumValueProperty =
DependencyProperty.Register("NumValue", typeof(string), typeof(UpDown),
new PropertyMetadata("1", new PropertyChangedCallback(OnNumChanged)));
private static void OnNumChanged(DependencyObject d,DependencyPropertyChangedEventArgs e)
{
var instannce = d.ToString();
}
In the MainWindow,I am going to bind the MainViewModel to the UserControl
MainViewModel.cs
public class MainViewModel: BaseViewModel
{
private string _myValue;
public string MyValue
{
get { return _myValue; }
set
{
_myValue = value;
OnPropertyChanged("MyValue");
}
}
}
MainWindow.xaml
<Window.DataContext>
<local:MainViewModel/>
</Window.DataContext>
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<local:UpDown Grid.Row="0" NumValue="{Binding MyValue}" x:Name="udGuestNum" Width="220" Margin="0 20"/>
<Button Name="btnOK" Grid.Row="1" Content="OK" Click="btnOK_Click"/>
</Grid>
The NumValue Binding is OneWay by default. Either explicitly set it to TwoWay
NumValue="{Binding MyValue, Mode=TwoWay}"
or make TwoWay the default:
public static readonly DependencyProperty NumValueProperty =
DependencyProperty.Register(
"NumValue", typeof(string), typeof(UpDown),
new FrameworkPropertyMetadata(
"1", FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnNumChanged));
numeric up/down control have already been developed...don't waste your time, you can even grab the code > https://github.com/xceedsoftware/wpftoolkit

Accessing DataContext properties in View

I'm hoping someone can give me a kick in the right direction, I'm currently learning WPF and MVVM - let's say its not been plain sailing. Basically I'm trying to access the properties of DataContext and bind them to a property in my view. I'll be completely honest, I've got myself in a bit of a tangle.
When the user clicks the button in question it fires the code below.
private void OnReceiptClick(object sender, RoutedEventArgs e)
{
var dialogBox = new DisplayReceiptView(((CheckMemberViewModel) this.DataContext).ReceiptViewModel);
dialogBox.ShowDialog();
}
My CheckMemberViewModel currently holds the 'Person' property I'm after, and at this stage DataContext is populated as expected.
The code behind my DisplayReceiptView looks like the following:
public DisplayReceiptView(ReceiptViewModel context) : this()
{
this.DataContext = context;
}
Once again everything seems correct, and finally in my XAML I have
<Grid DataContext="{Binding Path=Person}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="10"/>
<ColumnDefinition Width="150"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="10" />
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Label Grid.Column="1" Grid.Row="1">Name:</Label>
<TextBox Grid.Column="2" Grid.Row="1" Text="{Binding Path=Person.Forename}"></TextBox>
</Grid>
Unfortunately no matter what I've done, and I think where I'm up to at the moment is the closest I've been, the data doesn't seem to bind. Below is my ViewModel code for the properties
private Person _person;
public Person Person
{
get { return _person; }
set
{
if (value != _person)
{
_person = value;
OnPropertyChanged("Person");
}
}
}
Any help is greatly appreciated.
<TextBox Grid.Column="2" Grid.Row="1" Text="{Binding Path=Person.Forename}"></TextBox>
This is wrong as you are already bound to Person
<TextBox Grid.Column="2" Grid.Row="1" Text="{Binding Forename}"></TextBox>
Is all you need
<TextBox Grid.Column="2" Grid.Row="1" Text="{Binding Forename, Mode=TwoWay}"></TextBox>
Will save changes to the source and retrieve changes, but of course you will need to save context changes to make them permanent

WPF Databinding not working in both directions when DataGrid bound to Observable Collection of Properties with Sub properties

Excuse the wordy title, I'm having trouble with a succinct description. If I could come up with one, I could probably Google the right answer!
I am binding my DataGrid to an ObservableCollection of properties that themselves have properties. My grid is populated just fine, but when I edit the grid the changes are not getting back to my model.
I have an ObservableCollection
Normally, you'd just have some properties of MarriedCoupleRow, but I actually have something slightly more complicated. Each MarriedCoupleRow has some propties (Male, Female) which in turn expose properties (Height, Weight, Information). It's this Information that can be edited. Again, I can populate the grid just fine, but the setter property of Information is not hit when you edit the cell and tab off (or leave).
I'd appreciate any pointers or references, including how to better word my title!
Here's the simple code:
public class XMLDemoViewModel : ViewModelBase
{
public XMLDemoViewModel()
{
_rows = new ObservableCollection<MarriedCoupleRow>();
// create some data....
for (uint i = 0; i < 2;i++)
{
MarriedCoupleRow row = new MarriedCoupleRow();
row.Male = new HumanData();
row.Male.Height = (70 + i*5).ToString();
row.Male.Weight = 150+(i*30+1);
row.Male.Information = row.Male.Height + " " + row.Male.Weight;
row.Female = new HumanData();
row.Female.Height = (60 +i*3).ToString();
row.Female.Weight = 120+(i*10+5);
row.Female.Information = row.Female.Height + " " + row.Female.Weight;
_rows.Add(row);
}
}
#region Fields
private ObservableCollection<MarriedCoupleRow> _rows = null;
#endregion Fields
#region Properties
public ObservableCollection<MarriedCoupleRow> Rows
{
get
{
return _rows;
}
}
#endregion Properties
#region Commands
#endregion Commands
#region Private Methods
#endregion Private Methods
}
public class MarriedCoupleRow : ViewModelBase
{
private HumanData _Male = null;
public HumanData Male
{
get { return _Male; }
set
{
if (value != _Male)
{
_Male = value;
OnPropertyChanged("Male");
}
}
}
public HumanData Female { get; set; }
}
public class HumanData : INotifyPropertyChanged
{
public string Height { get; set; }
public uint Weight { get; set; }
private string _friendlyName;
public string Information
{
get
{
return _friendlyName;
}
set
{
if (_friendlyName != value)
{
_friendlyName = value;
OnPropertyChanged("Information");
}
}
}
}
And here's the XAML:
<Window x:Class="XMLDemo.Views.XMLDemoView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="XMLDemoView" Height="600" Width="1152">
<DockPanel>
<StackPanel Orientation="Horizontal" Height="120" DockPanel.Dock="Bottom">
<StackPanel Orientation="Horizontal">
<GroupBox Width="249" BorderThickness="2" Height="90">
<GroupBox.Header>
<TextBlock FontSize="12" FontWeight="Bold">Control</TextBlock>
</GroupBox.Header>
<Grid Height="64" Width="223">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.5*" />
<ColumnDefinition Width="0.5*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="0.5*"/>
<RowDefinition Height="0.5*"/>
</Grid.RowDefinitions>
</Grid>
</GroupBox>
</StackPanel>
</StackPanel>
<DataGrid ItemsSource="{Binding Path=Rows, UpdateSourceTrigger=PropertyChanged}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTemplateColumn>
<DataGridTemplateColumn.HeaderTemplate >
<DataTemplate>
<Grid ShowGridLines="True">
<Grid.RowDefinitions>
<RowDefinition />
</Grid.RowDefinitions>
<TextBlock Text="Male" />
</Grid>
</DataTemplate>
</DataGridTemplateColumn.HeaderTemplate>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<TextBox Text="{Binding Male.Height}" IsEnabled="False" Grid.Row="0"></TextBox>
<TextBox Text="{Binding Male.Weight}" IsEnabled="False" Grid.Row="1"></TextBox>
<TextBox Text="{Binding Male.Information, Mode=TwoWay}" Grid.Row="2"></TextBox>
</Grid>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn>
<DataGridTemplateColumn.HeaderTemplate >
<DataTemplate>
<Grid ShowGridLines="True">
<Grid.RowDefinitions>
<RowDefinition />
</Grid.RowDefinitions>
<TextBlock Text="Female" />
</Grid>
</DataTemplate>
</DataGridTemplateColumn.HeaderTemplate>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Grid >
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<TextBox Text="{Binding Female.Height}" IsEnabled="False" Grid.Row="0"></TextBox>
<TextBox Text="{Binding Female.Weight}" IsEnabled="False" Grid.Row="1"></TextBox>
<TextBox Text="{Binding Female.Information}" Grid.Row="2"></TextBox>
</Grid>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</DockPanel>
Your TextBox.Text bindings need to be set to updatesource on propertychanged.
<TextBox Text="{Binding Male.Information, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Grid.Row="2"></TextBox>
There must be something goofy going on with LostFocus which is the default. I tested this using your code.
I Like your post. As I seen from the coding you are using Complex property binding with DataGrid. Also complex property changes won't be reflect in DataGrid.
However you can achieve this requirement in sample level. I will try to make the sample and let you know.
Regards,
Riyaj Ahamed I

listBox DataTemplate not picking up values

I am learning to use listBox in WPF with dataTemplate using the examples from MSDN, I can render a listBox bound to an ObservableCollection as a source and by overriding the ToString method.
However, I need to render an image and some texblocks for every item. Here's my XAML:
<Grid x:Class="MyAddin.WPFControls"
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:c="clr-namespace:MyAddin"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
Background="Transparent"
HorizontalAlignment="Stretch" Width="auto"
Height="215" VerticalAlignment="Stretch" ShowGridLines="False">
<Grid.Resources>
<c:People x:Key="MyFriends"/>
</Grid.Resources>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBlock HorizontalAlignment="Left"
IsManipulationEnabled="True"
Height="20" Width="300">Activity Feed</TextBlock>
<ListBox Grid.Row="1" Name="listBox1" IsSynchronizedWithCurrentItem="True"
BorderThickness="0" ScrollViewer.VerticalScrollBarVisibility="Auto"
VerticalContentAlignment="Stretch" Margin="0,0,0,5" Background="Transparent">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="60"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Border Margin="5" BorderBrush="Black" BorderThickness="1">
<Image Source="{Binding Path=Avatar}" Stretch="Fill" Width="50" Height="50" />
</Border>
<StackPanel Grid.Column="1" Margin="5">
<StackPanel Orientation="Horizontal" TextBlock.FontWeight="Bold" >
<TextBlock Text="{Binding Path=Firstname }" />
</StackPanel>
<TextBlock Text="{Binding Path=Comment}" />
</StackPanel>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
My Collection class is as following:
public class People : ObservableCollection<Person>
{ }
public class Person
{
private string firstName;
private string comment;
private Bitmap avatar;
public Person(string first, string comment, Bitmap avatar)
{
this.firstName = first;
this.comment = comment;
this.avatar = avatar;
}
public string FirstName
{
get { return firstName; }
set { firstName = value; }
}
public string Comment
{
get { return comment; }
set { comment = value; }
}
public Bitmap Avatar
{
get { return avatar;}
set { avatar = value; }
}
public override string ToString()
{
return firstName.ToString();
}
}
Once my addin is loaded, I am downloading my data and setting the itemsSource.
People p = new People();
p.Add(new Person("Willa", "Some Comment", myAvatar));
p.Add(new Person("Isak", "Some Comment", myAvatar));
p.Add(new Person("Victor", "Some Comment", myAvatar));
this.wpfControl.listBox1.ItemsSource = p;
The problem I am facing is that the items are being rendered as empty rows whereas If I remove the dataTemplate, the items are rendered fine with their firstName.
Don't see anything wrong with the bindings themselves, but your avatar type seems off, WPF expects ImageSource (i do not know if there is any implicit convertion between Bitmap and ImageSource, check for binding errors to find out).

Binding Items inside a DataTemplate with Items from another DataTemplate

I have two Data Template (one for drawing[draw] and another for Input Data[data]) Also I have the two ContentControls which uses the above DataTemplates.
I want the both DataTemplate's elements to be binded so that when the user fills in a field in the data form DateTemplate it automatically updates the draw Template as well.
How can I bind the elements in draw DataTemplate with the elements of data DataTemplate.
There is no backend data at all. User picks up a value from a combobox and based upon the value selected in combobox I update the two ContentControls with relevant draw and data DataTemplates. User fill in the relevant fields in the data form and draw template draws those elements based upon some business Rules.
-----
<DataTemplate x:Key="data">
<Grid Grid.Row="0" Background="#FFFFFFFF" Name="DocumentRoot" VerticalAlignment="Top">
<Grid.RowDefinitions>
<RowDefinition Height="auto" />
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<Grid Margin="10" VerticalAlignment="Top">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100" />
<ColumnDefinition Width="200" />
</Grid.ColumnDefinitions>
<TextBlock Text="Heading Text" Grid.Row="1"/>
<TextBlock Text="Ticket Text" Grid.Row="2"/>
-----
<TextBox x:Name="txtHeading" Text="Heading Text" Grid.Row="1" Grid.Column="1"/>
<TextBox x:Name="txtTicketText" Text="Ticket Text" Grid.Row="2" Grid.Column="1"/>
-----
</Grid>
</Grid>
</DataTemplate>
<ContentControl Content="{Binding ElementName=cboTemplates, Path=SelectedItem.Name}"
ContentTemplateSelector="{StaticResource formTemplateSelector}">
</ContentControl>
Any ideas how can I bind the two elements from inside different DataTemplates?
Thanks in advance
Consider creating class (named View Model) and bind both templates to single instance of that class (this is Model-View-ViewModel design pattern). Otherwise you probably will have very complex bindings contains hardcoded logical tree.
Why don't you bind one object (of class with a Draw property and a Data property) to both the templates. When one template changes Data property in the object, you can refresh Draw property in the object which in turn will update the Draw template.
Updated
Example :
Window Content
<Grid>
<StackPanel>
<ContentControl DataContext="{Binding}">
<ContentControl.Template>
<ControlTemplate>
<Rectangle Fill="{Binding Background}"
Width="200"
Height="200" />
</ControlTemplate>
</ContentControl.Template>
</ContentControl>
<ContentControl DataContext="{Binding}">
<ContentControl.Template>
<ControlTemplate>
<TextBox Text="{Binding ColorText}" />
</ControlTemplate>
</ContentControl.Template>
</ContentControl>
</StackPanel>
</Grid>
Code Behind
public partial class MultiViewWindow : Window
{
public MultiViewWindow()
{
InitializeComponent();
DataContext = new BackgroundInfo();
}
}
public class BackgroundInfo : INotifyPropertyChanged
{
protected String _colorText;
public String ColorText
{
get
{
return _colorText;
}
set
{
_colorText = value;
RaisePropertyChanged("ColorText");
RaisePropertyChanged("Background");
}
}
public Brush Background
{
get
{
try
{
return new SolidColorBrush((Color)ColorConverter.ConvertFromString(ColorText));
}
catch (Exception)
{
return new SolidColorBrush(Colors.Transparent);
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
void RaisePropertyChanged(String propertyName)
{
PropertyChangedEventHandler temp = PropertyChanged;
if (temp != null)
{
temp(this, new PropertyChangedEventArgs(propertyName));
}
}
}

Resources