WPF MVVM - Combo box inside data grid [duplicate] - c#

This question already has answers here:
Why does WPF support binding to properties of an object, but not fields?
(2 answers)
Closed 8 months ago.
I Have a data grid of objects (CopyObject) , each object contains list of objects (PGroupGridObject) that i want to display inside combo box.
My View Model :
private ObservableCollection<CopyObject> foldersToCopy;
public ObservableCollection<CopyObject> FoldersToCopy
{ get => foldersToCopy; set { foldersToCopy = value; OnPropertyChanged("FoldersToCopy"); } }
CopyObject class :
public class CopyObject
{
public ObservableCollection<PGroupGridObject> pGroups;
public CopyObject(string s , ObservableCollection<PGroupGridObject> pGroups)
{
Name = s;
IsFolder = (File.GetAttributes(Name) & FileAttributes.Directory) == FileAttributes.Directory;
this.pGroups = pGroups;
}
public string Name { get; set; }
}
PGroupGridObject class :
public class PGroupGridObject : ViewModelBase
{
public PGroupGridObject(object o)
{
Object = (DeployTool.Domain.Model.PGroup)o;
PGroupName = Object.Name;
ProductName = Object.Project_Product.Name;
}
private bool isChecked { get; set; }
private string pGroupName;
public string PGroupName
{
get { return pGroupName; }
set
{
pGroupName = value;
OnPropertyChanged("PGroupName");
}
}
public bool IsChecked
{
get { return isChecked; }
set
{
isChecked = value;
OnPropertyChanged("IsChecked");
}
}
}
my xaml :
<DataGrid ItemsSource="{Binding FoldersToCopy}" Grid.Row="7" Grid.Column="1" SelectionUnit="FullRow" RowHeaderWidth="0" SelectedItem="{Binding CopyObjectSelected}"
Style="{StaticResource DataGridStyle}" d:ItemsSource="{d:SampleData ItemCount=2}" AutoGenerateColumns="False"
MinHeight="60" MaxHeight="180" Margin="0,10,0,10"
Foreground="White" Background="#292929" FontSize="16" BorderThickness="0" HorizontalAlignment="Right" MaxWidth="800" MinWidth="600" >
<DataGrid.Columns>
<DataGridTextColumn Header="File Path" Binding="{Binding Name}" CanUserResize="True" MinWidth="520"/>
<DataGridComboBoxColumn Header="PGroups"
ItemsSource="{Binding pGroups, UpdateSourceTrigger=PropertyChanged}"
DisplayMemberPath="{Binding PGroupName}"
/>
</DataGrid.Columns>
</DataGrid>
All the examples I found show Bind from the View Model and not from the object in the grid.
the goal eventually is to display check box inside every group in combo box.
I would appreciate help.

pGroups must be a public property for you to be able to bind to it:
public ObservableCollection<PGroupGridObject> pGroups { get; }
Also, the DisplayMemberPath should be set to a string that matches the name of a property of a PGroupGridObject:
DisplayMemberPath="PGroupName"

Related

Binding ListView inside combobox item not binding(showing)

I'm trying to create a Combobox with multiple items and header and way I'm approaching is to create a listView (or DataGrid) inside the Combobox
but for some reason, the items won't bind
as you can see no items in the list
XAML (when ComboBox.ItemTemplate have used the items showed properly with no headers of course)
<ComboBox
materialDesign:HintAssist.Hint="בחר מתכון מהרשימה">
<!--ItemsSource = "{Binding Path=Recipes}" >-->
<!--DisplayMemberPath = "Description">-->
<ListView ItemsSource="{Binding Recipes}"
SelectedItem="{Binding Path=SelectedRecipe}"
Height="200" ScrollViewer.VerticalScrollBarVisibility="Visible" IsEnabled="False" Focusable="False">
<ListView.View>
<GridView>
<GridViewColumn Width="130" Header="Description" DisplayMemberBinding="{Binding Description}" />
</GridView>
</ListView.View>
</ListView>
</ComboBox>
ViewModel (im using Prism as my MVVM library)
public ObservableCollection<Recipes> Recipes
{
get { return _recipes; }
set { SetProperty(ref _recipes, value); }
}
private ObservableCollection<Recipes> _recipes = new ObservableCollection<Recipes>();
private async void FillRecipesList() //this is call on program startup
{
if (Recipes != null && Recipes.Count > 0)
{
Recipes.Clear();
}
var result = await _mSql.GetRecipes();
if (result.Count() > 0)
Recipes.AddRange(result);
}
Model
public class Recipes
{
public long AutoNum { get; set; }
public int? RecipeCode { get; set; }
public int? RecipeVersion { get; set; }
public string Description { get; set; }
}
You should try to call the method
FillRecipesList()
in your ViewModel's constructor

How to properly bind Checkbox property

I am working on a wpf application and I am dealing with checkboxes now
The problem when I set the Ischecked property to "True" like this:
<CheckBox Visibility="{Binding checkVisibility}" IsChecked="true"
IsEnabled="True"></CheckBox>
I get my checkbox checked
But when I try to bind a booléan property that it's value is "true" i get my checkbox always unchecked
I can't see where is the proplem
this is my xaml
<CheckBox Visibility="{Binding checkVisibility}" IsChecked="{Binding Path=test,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}" IsEnabled="True"></CheckBox>
this is my property
public bool _test = true;
public bool test {
get {
return _test;
}
set {
if (_test == value) {
return;
}
_test = value;
RaisePropertyChanged("test");
}
}
I want my checkbox to reflect my property value and vice versa but it's not the case as my checkbox is always unchecked
I am missing something?
Edit
Here is my VM:
namespace X{
public class MyViewModel :
{
public MyViewModel()
{
TestCheckbox();
}
#Region Properties
public bool _test1 = true;
public bool test1
{
get
{
return _test1;
}
set
{
if (_test1 == value)
{
return;
}
_test1 = value;
RaisePropertyChanged("test1");
}
}
ObservableCollection<Output> _output_List;
public ObservableCollection<Output> output_List
{
get { return _output_List; }
set
{
if (_output_List == value) return;
_output_List = value;
RaisePropertyChanged("output_List");
}
}
#EndRegion
#Region ButtonCommand
private RelayCommand _SetOutputPropertiesCommand;
public RelayCommand SetOutputPropertiesCommand => _SetOutputPropertiesCommand
?? (_SetOutputPropertiesCommand = new RelayCommand(
() =>
{
foreach (Output item in output_List)
{
item.myvalue=Test2;
}
}
}));
#EndRegion
#Region Method
public void TestCheckbox()
{
Console.Writeline(Test2);
}
#EndRegion
}
public class Output
{
public string label { get; set; }
public string type { get; set; }
public bool myvalue { get; set; }
public bool Test2 { get; set; }
[System.ComponentModel.DataAnnotations.Schema.NotMapped]
[JsonIgnore]
public string checkVisibility { get; set; }
}
}
My Xaml : my checkboxes are integrated in a DataGrid view
<DataGrid x:Name ="GridO" Style="{x:Null}"
ItemsSource= "{Binding output_List,UpdateSourceTrigger=PropertyChanged}"
AutoGenerateColumns="False" CellStyle="{StaticResource Body_Content_DataGrid_Centering}"
Margin="5,0" IsReadOnly="True" SelectionMode="Single" RowHeight="50" Height="Auto">
<DataGrid.Columns>
<DataGridTextColumn Width="40*" Binding="{Binding label}">
<DataGridTextColumn.HeaderTemplate>
<DataTemplate>
<TextBlock Text="Input"></TextBlock>
</DataTemplate>
</DataGridTextColumn.HeaderTemplate>
</DataGridTextColumn>
<DataGridTextColumn Width="40*" Binding="{Binding type}">
<DataGridTextColumn.HeaderTemplate>
<DataTemplate>
<TextBlock Text = "Type"></TextBlock>
</DataTemplate>
</DataGridTextColumn.HeaderTemplate>
</DataGridTextColumn>
<DataGridTemplateColumn Width="20*" >
<DataGridTemplateColumn.Header>
<TextBlock Text="Value" />
</DataGridTemplateColumn.Header>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox Margin="20,0,0,0" Visibility="{Binding checkVisibility }" IsChecked="{Binding Test2,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" IsEnabled="True"></CheckBox>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
<Button x:Name="Valid_output" Cursor="Hand" Background="Transparent" Height="55" Width="140" Margin="0,0,20,0" Command="{Binding SetOutputPropertiesCommand}" >
The bind is Working with "Test2" and not working with "Test1" which not in the same class as Test2
NB: the Button command(which is in the same class as "Test1") is working well
My DataTemplate: are in the App.xaml
xmlns:v="clr-namespace:X.View"
xmlns:vm="clr-namespace:X"
<DataTemplate DataType="{x:Type vm:MyViewModel}">
<v:MyWindow/>
I see the main problem in the DataGrid. You set ItemsSource to a collection, so for every row in the DataGrid the data source is one item in that collection. Not your MyViewModel.
This is the reason, why the Test2 is working - it is in the class which instances are in the collection.
You could try to add CheckBox to the window without DataGrid and bind the Test1 - it should work.
If you really want to use some property from your MyViewModel, you can, but it is not that easy. You have to have there something like:
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:YourNamespace"
<!--...something...-->
<DataGrid.Resources>
<local:BindingProxy x:Key="Proxy" Data="{Binding}" />
</DataGrid.Resources>
<!--...something...-->
And then your binding in the DataGrid will look like this:
IsChecked="{Binding Data.Test1, Source={StaticResource Proxy}}"
Of course I don't know the exact settings of your application so you will have to complete/change the code according to them.
I suggest you to add a ViewModelBase class, like that
public abstract class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName =
null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
Extends your ViewModel with this ViewModelBase class and implements your property
private bool myProperty;
public bool MyProperty { get; set; OnPropertyChanged(); }
Then you just have to bind on your property
<CheckBox IsChecked="{Binding MyProperty}"></CheckBox>
EDIT: To set your ViewModel as DataContext for your View you can set it from the code
MyView.DataContext = new MyViewModel();
or from the view, in the Window/User Control
<Window x:Class="MyApplication.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MyApplication"
Title="MainWindow" Height="350" Width="525"
DataContext="local.MyViewModel">

Multiple rows in datagrid are changing when only the row explicitly changed should be

I have a two datagrids, both using identical xaml (other than one having an extra column). One is in the main window, the other is inside a usercontrol. Both are bound to a collection of the same items (one is currently an ObservableCollection, the other is an array). Project uses MVVM (or a close approximation).
The array/main window one works correctly - the Location combobox loads in the selected value (where it isn't null) and changing that value only affects the row it is changed in.
The ObservableCollection/usercontrol one does not. The values in the Location column do not load when the window opens, until you scroll down then back up again. Changing the Location combobox changes the value displayed in every visible row (or every row if virtualisation is turned off)... including in the disabled comboboxes. The same does not happen for the Bonding Level combobox, which is handled essentially identically. This happens whether the data presented is an array or an ObservableCollection.
Each instance of the class used to produce a row should be entirely separate, there's no codebehind to mess with values, and extremely similar xaml and c# in another file using the exact same type in the collection works. I am lost!
Screenshots are as follows:
Correct behaviour (Main window, array)
https://i.imgur.com/SJIsTOT.png (Loaded immediately, no values in disabled comboboxes)
https://i.imgur.com/cmjaPoR.png (Single row changes)
Broken behaviour (Usercontrol embedded into tabcontrol, ObservableCollection)
https://i.imgur.com/yC3iAas.png (not loading on window opened)
https://i.imgur.com/aQgPMCN.png (loaded after scroll, including invalid values)
https://i.imgur.com/dqo39aB.png (one combobox changed, all rows change)
XAML for the DataGrid and the misbehaving combobox column (no binding errors):
<DataGrid Grid.Row ="1" Width="Auto" Height="Auto" AlternatingRowBackground="#FBE9D9" AlternationCount="2"
AutoGenerateColumns="False" GridLinesVisibility="None"
ItemsSource="{Binding Familiars}" IsSynchronizedWithCurrentItem="True">
<DataGrid.InputBindings>
<MouseBinding MouseAction="LeftDoubleClick" Command="{Binding OpenDataFamiliarWindow}" CommandParameter="{Binding Familiars/}"/>
</DataGrid.InputBindings>
<DataGrid.Resources>
<local_c:OwnedToBoolConverter x:Key="OwnedToBoolConverter"/>
<local_c:EnemyTypeToColourConverter x:Key="EnemyTypeToColour"/>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Transparent"/>
</DataGrid.Resources>
<DataGridTemplateColumn Header="Location" Width="Auto" IsReadOnly="False">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox ItemsSource="{Binding AvailableLocationTypes}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" MinWidth="90"
SelectedItem="{Binding Info.Location, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
IsSynchronizedWithCurrentItem="True" IsEnabled="{Binding Info.Owned, Converter={StaticResource OwnedToBoolConverter}}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Converter={StaticResource DescConverter}, Mode=OneTime}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid>
The class that the UserControl is designed to bind to (and the only bit that differs from the working use of essentially the same datagrid):
public class ColiseumVenue : INotifyPropertyChanged
{
public BitmapImage HeaderImage { get; private set; }
public string Name { get; private set; }
public ObservableCollection<FamiliarViewModel> Familiars { get; private set; } = new ObservableCollection<FamiliarViewModel>();
private IModel m_Model;
public ColiseumVenue(IModel model, string name, IEnumerable<FamiliarViewModel> familiars)
{
Name = name;
m_Model = model;
HeaderImage = ImageLoader.LoadImage(Path.Combine(ApplicationPaths.GetViewIconDirectory(), name + ".png"));
foreach(var familiar in familiars)
{
Familiars.Add(familiar);
}
}
public ColiseumView Window { get; set; }
private BaseCommand m_openDataFamiliarWindow;
public ICommand OpenDataFamiliarWindow
{
<snip>
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
The public variables of the FamiliarViewModel class are:
public class FamiliarViewModel : INotifyPropertyChanged
{
public FamiliarInfo Info { get; set; }
public LocationTypes[] AvailableLocationTypes { get; private set; }
public OwnershipStatus[] AvailableOwnershipStatuses { get; private set; }
public BondingLevels[] AvailableBondingLevels { get; private set; }
public BookmarkState[] AvailableBookmarkStates { get; private set; }
}
The parts of the FamiliarInfo class that are bound to are:
public ICRUD<OwnedFamiliar> OwnedFamiliar
{
get { return m_OwnedFamiliar; }
set
{
if(m_OwnedFamiliar != value)
{
m_OwnedFamiliar = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Owned"));
}
}
}
public OwnershipStatus Owned => OwnedFamiliar != null ? OwnershipStatus.Owned : OwnershipStatus.NotOwned;
public BondingLevels? BondLevel
{
get
{
return OwnedFamiliar?.Fetch()?.BondingLevel;
}
set
{
if (value.HasValue)
{
OwnedFamiliar?.Update(f => f.BondingLevel = value.Value);
}
}
}
public LocationTypes? Location
{
get
{
return OwnedFamiliar?.Fetch()?.Location;
}
set
{
if (value.HasValue)
{
OwnedFamiliar?.Update(f => f.Location = value.Value);
}
}
}
This turned out to be the same issue as: WPF MVVM DataGridComboboxColumn change one row updates all
The selected answer (setting IsSynchronizedWithCurrentItem to null) worked.

WPF data binding to Window DataContext object properties

**[Solved]**this is my first question asked here, so some mistakes could pass.
In my WPF app I want to bind in "two-way mode" all controls to corresponding properties in special object instance BuildingManagementSystem, which I'd like to set as Window DataContext.
But nothing works (data are not displayed). What is the right way to bind it?
Here is my code:
public partial class MainWindow : Window
{
BuildingManagementSystem bms { get; set; }
public MainWindow()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(Window1_Loaded);
}
void Window1_Loaded(object sender, RoutedEventArgs e)
{
bms = new BuildingManagementSystem();
this.DataContext = bms;
}
public class BuildingManagementSystem
{
public string Name { get; set; }
public readonly FireAlarmSystem FireAlarmSystem;
public BuildingManagementSystem()
{
FireAlarmSystem = new FireAlarmSystem();
}
}
class FireAlarmSystem
{
private int alarmSmokeRate, currentSmokeRate;
public List<PowerConsumer> Devices { get; set; }
public int CurrentSmokeRate
{
get { return currentSmokeRate; }
set { SetField(ref currentSmokeRate, value, () => CurrentSmokeRate); }
}
public FireAlarmSystem()
{
Devices = new List<PowerConsumer>();
}
}
class PowerConsumer
{
public string Name { get; set; }
public double Power { get; set; }
public int Priority { get; set; }
public bool Enabled { get; set; }
}
XAML:
<DataGrid Name="FireAlarmGrid" HorizontalAlignment="Left" Margin="10,51,0,0" CanUserAddRows="True"
CanUserDeleteRows="True" VerticalAlignment="Top" AutoGenerateColumns="False" ItemsSource="{Binding FireAlarmSystem.Devices}" >
<DataGrid.RowValidationRules>
<local:FireValidationRule ValidationStep="UpdatedValue"/>
</DataGrid.RowValidationRules>
<DataGrid.Columns>
<DataGridCheckBoxColumn Header="Enabled" Binding="{Binding Enabled}"></DataGridCheckBoxColumn>
<DataGridTextColumn Header="Name" Binding="{Binding Name,ValidatesOnExceptions=True }" >
</DataGridTextColumn>
<DataGridTextColumn Header="Power" Binding="{Binding Power}"></DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
<TextBox Name="tbCurrentSmokeRate" Text="{Binding Path=FireAlarmSystem.CurrentSmokeRate, Mode=TwoWay}" VerticalAlignment="Top" Width="70"/>
I personally like to create static instances of the viewmodel as shown here:
<Window.Resources>
<ViewModels:MainWindowVM x:Key="VM"></ViewModels:MainWindowVM>
When I do that then binding is easy because the properites page finds the properties for you in VS.
<StackPanel Grid.Column="0" Margin="5,5,5,0"
DataContext="{Binding Source={StaticResource VM}}">
But remember you need to add the namespace
xmlns:ViewModels="clr-namespace:MyWPF.ViewModels"
xmlns:Views="clr-namespace:MyWPF.Views"
This allow property binding like this:
<Views:UcTitle x:Name="XTitle" ></Views:UcTitle>
<Views:UcLegendTitle x:Name="XLegendTitle"/>
<Views:UcSeriesTitle x:Name="XSeriesTitle" />
<Views:UcSeriesTypes x:Name="XSeriesTypes"/>
And you don't have to type any of the names in...
In your case you are not using a ViewModel but you are setting the data-context correctly. So this can only be either no data to display or improper property bind. Remember for this to work you need three things 1) DataContext 2) Vales and 3) Proper binding by Name... It's the third one that trips up folks a lot when just starting out with the great WPF binding system.
Couple of mistakes out here
Seems like BuildingManagementSystem is intended to be your data-context
In place of BuildingManagementSystem bms { get; set; } write the below code:
BuildingManagementSystem bms =new BuildingManagementSystem ();
You need to implement INotifyPropertyChanged event in your ViewModels to reflect the changes on UI
If you intent is to assign values to each of the underlying child view-models, make use of parameterized constructors to pass and assign values. Simply instantiating the child viewModels in parent will not serve any purpose.
To get MVVM working...
You will need to update your View Model to Implement INotifyPropertyChanged to let wpf know your property changed
Use Observable collections instead of lists, ObservableCollections have the wiring to let Datagrid listview, listboxes know items in the collections have changed
Change the Field to a Property so WPF will see it...
<DataGrid Name="FireAlarmGrid" HorizontalAlignment="Left" Margin="10,51,0,0" CanUserAddRows="True"
CanUserDeleteRows="True" VerticalAlignment="Top" AutoGenerateColumns="False" ItemsSource="{Binding FireAlarmSystem.Devices}" >
<DataGrid.RowValidationRules>
<local:FireValidationRule ValidationStep="UpdatedValue"/>
</DataGrid.RowValidationRules>
<DataGrid.Columns>
<DataGridCheckBoxColumn Header="Enabled" Binding="{Binding Enabled,Mode=TwoWay}"></DataGridCheckBoxColumn>
<DataGridTextColumn Header="Name" Binding="{Binding Name,ValidatesOnExceptions=True,Mode=TwoWay }" >
</DataGridTextColumn>
<DataGridTextColumn Header="Power" Binding="{Binding Power,Mode=TwoWay}"></DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
<TextBox Name="tbCurrentSmokeRate" Text="{Binding Path=FireAlarmSystem.CurrentSmokeRate, Mode=TwoWay}" VerticalAlignment="Top" Width="70"/>
public class BuildingManagementSystem : INotifyPropertyChanged
{
private string _Name;
public string Name
{
get { return _Name; }
set
{
if (_Name != value)
{
_Name = value;
PropertyChanged(this, new PropertyChangedEventArgs("Name"));
}
}
}
private FireAlarmSystem _fireAlarmSystem;
public FireAlarmSystem FireAlarmSystem { get { return _fireAlarmSystem; } }
public BuildingManagementSystem()
{
_fireAlarmSystem = new FireAlarmSystem();
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged = delegate { };
#endregion
}
public class FireAlarmSystem : INotifyPropertyChanged
{
private int alarmSmokeRate, currentSmokeRate;
public ObservableCollection<PowerConsumer> Devices { get; set; }
public int CurrentSmokeRate
{
get { return currentSmokeRate; }
set
{
//SetField(ref currentSmokeRate, value, () => CurrentSmokeRate);
PropertyChanged(this, new PropertyChangedEventArgs("CurrentSmokeRate"));
}
}
public FireAlarmSystem()
{
Devices = new ObservableCollection<PowerConsumer>();
//Create some test data...
Devices.Add(new PowerConsumer() { Name = "One", Enabled = true, Power = 100, Priority = 1 });
Devices.Add(new PowerConsumer() { Name = "two", Enabled = false, Power = 101, Priority = 2 });
Devices.Add(new PowerConsumer() { Name = "three", Enabled = false, Power = 103, Priority = 3 });
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged = delegate { };
#endregion
}
public class PowerConsumer
{
public string Name { get; set; }
public double Power { get; set; }
public int Priority { get; set; }
public bool Enabled { get; set; }
}
Thanks to all, I've found a mistake, it was defining FireAlarmSystem as readonly, it shold be a property.
2 Stuart Smith, you're right with INotifyPropertyChanged, but I have an abstract class-ancestor BuildingSystem, which implements this interface. I've forgot to post it.

Datagrid auto add item with data of parent

I have datagrid, which should allow user add row. But it should add item where one of the field defined by the one of the model properties. Have anybody an idea how to do it.
Code like this:
public class OrderWindowModel : BaseModel
{
public ObservableCollection<GoodM> Goods { get; set; }
public Service Service { get; set; }
}
public class GoodM : BaseModel
{
public Service Service { get; set; }
public List<Good> Goods
{
get{ return Service.GoodsL; }
}
public Good CurrGood { get; set; }
}
And xaml
<custom:DataGrid Margin="5" Grid.Row ="1" CanUserAddRows="True" CanUserDeleteRows="True"
AutoGenerateColumns="False" SnapsToDevicePixels="True" SelectedIndex="0"
CanUserReorderColumns="True" ItemsSource="{Binding Goods}" Grid.ColumnSpan="2">
<custom:DataGrid.Columns>
<custom:DataGridComboBoxColumn Header="Товар" DisplayMemberPath="{Binding Name}"
SelectedItemBinding="{Binding CurrGood}" ItemsSource="{Binding Goods}" Width="*">
</custom:DataGridComboBoxColumn>
</custom:DataGrid.Columns>
</custom:DataGrid>
You can do that using code behind. Hook to InitializingNewItem event in your XAML:
<DataGrid InitializingNewItem="DataGrid_InitializingNewItem"/>
In the handler you will get NewItem added where you can set the value for your field:
private void DataGrid_InitializingNewItem(object sender,
InitializingNewItemEventArgs e)
{
if (e.NewItem != null)
{
((GoodM)newItem).Service = // Set value here;
}
}

Categories