logo
down
shadow

Two-way binding in DataGrid: source not updated


Two-way binding in DataGrid: source not updated

By : P K Arun Kumar
Date : November 21 2020, 01:01 AM
wish help you to fix your issue This appears to be a bug in DataGrid when using cell templates, etc. For whatever reason, the source will simply not be updated unless UpdateSourceTrigger is explicitly set. What is odd is that the the UpdateSourceTrigger will be set to 'Default' but acts like it is set to 'Explicit'.
To demonstrate the bug, or unexpected behaviour, I have taken your example, and tweaked it a bit. You can click on the various user controls and see that the default two way bindings work for everything, except for those items in the grid.
code :
<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication1"
        Title="MainWindow" Height="350" Width="525">

    <StackPanel>

        <DataGrid x:Name="grid" Grid.Row="1" AutoGenerateColumns="False" IsReadOnly="True" ItemsSource="{Binding Path=GameList}" MinHeight="100" >
            <DataGrid.Columns>
                <DataGridTextColumn Header="Title" Binding="{Binding Title}" />
                <DataGridTemplateColumn Header="Rating">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <local:MyControl Number="{Binding Path=Rating}" Loaded="TemplateControlLoaded" />
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>

        <ListBox Name="lst" ItemsSource="{Binding GameList}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <ListBoxItem>
                        <local:MyControl Number="{Binding Rating}" />
                    </ListBoxItem>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
        <local:MyControl x:Name="ctl" Loaded="MyControl_Loaded" Number="{Binding Path=Rating}" />
    </StackPanel>

</Window>
// ============================================================================================================================
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            grid.DataContext = new MyClassContainer();
            lst.DataContext = new MyClassContainer();
            ctl.DataContext = new MyClass();
        }

        private void TemplateControlLoaded(object sender, RoutedEventArgs e)
        {
            BindingExpression be = (sender as FrameworkElement).GetBindingExpression(MyControl.NumberProperty);
            Console.WriteLine("Template trigger = " + be.ParentBinding.UpdateSourceTrigger.ToString());
        }

        private void MyControl_Loaded(object sender, RoutedEventArgs e)
        {
            BindingExpression be = (sender as FrameworkElement).GetBindingExpression(MyControl.NumberProperty);
            Console.WriteLine("Instance trigger = " + be.ParentBinding.UpdateSourceTrigger.ToString());
        }
    }


    // ============================================================================================================================
    public class MyClassContainer
    {
        public List<MyClass> GameList { get; set; }

        public MyClassContainer()
        {
            GameList = new List<MyClass>();
            GameList.Add(new MyClass()
            {
                Rating = 150
            });
        }
    }


    // ============================================================================================================================
    public class MyClass : INotifyPropertyChanged
    {


        private int _Rating;
        public int Rating
        {
            get { return _Rating; }
            set
            {
                _Rating = value; NotifyChange("Rating");
                Console.WriteLine("changed!");
            }
        }

        private void NotifyChange(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }


        public event PropertyChangedEventHandler PropertyChanged;
    }
   <UserControl x:Class="WpfApplication1.MyControl"
                 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" 
                 mc:Ignorable="d" 
                 d:DesignHeight="300" d:DesignWidth="300" x:Name="this">
        <Grid Background="Red" PreviewMouseDown="Grid_PreviewMouseDown">
            <TextBlock Text="{Binding ElementName=this, Path=Number}" FontWeight="Bold" />
        </Grid>
    </UserControl>
public partial class MyControl : UserControl
    {
        public MyControl()
        {
            InitializeComponent();
        }

        public static readonly DependencyProperty NumberProperty = DependencyProperty.Register("Number", typeof(int), typeof(MyControl), new FrameworkPropertyMetadata(0, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
        public int Number
        {
            get { return (int)GetValue(NumberProperty); }
            set { SetValue(NumberProperty, value); }
        }

        private void Grid_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            e.Handled = true;
            this.Number = 1000;
        }

    }


Share : facebook icon twitter icon
WPF DataGrid ItemsSource doesn't get updated on changing source

WPF DataGrid ItemsSource doesn't get updated on changing source


By : pyh0603
Date : March 29 2020, 07:55 AM
help you fix your problem TableProperty class has to implement INotifyPropertyChanged and raise it properly.
MVVM DataGrid SelectedItem binding doesn’t get updated

MVVM DataGrid SelectedItem binding doesn’t get updated


By : Mehul Makwana
Date : March 29 2020, 07:55 AM
help you fix your problem EDIT: SelectionUnit=Cell dont work with SelectedItem
thats the normal mvvm way:
code :
 public class MyObject {}
 public class MyViewmodel
 {
    public ObservableCollection<MyObject> MyItems {get;set;}
    public MyObject MySelectedItem {get;set;}

 }
 <DataGrid ItemsSource="{Binding MyItems}" SelectedItem="{Binding MySelectedItem, Mode=TwoWay}"/>
wpf fire PropertyChanged event in binding source that binding gets updated

wpf fire PropertyChanged event in binding source that binding gets updated


By : queldis
Date : March 29 2020, 07:55 AM
like below fixes the issue It looks like the TextBlock source is looking at a static resource for the Validations class and the Validations called in your NumTbViewModel is NOT the same as the static resource. A solution could be to add a property to NumTbViewModel.cs and point your binding to that property so the Validations class instances will be the same. In NumTbViewModel.cs add:
code :
Validations _val;
    public Validations Val
    {
        get { return _val; }
        set 
        {
            _val = value;
            this.OnPropertyChanged("Val");
        }
    }
<TextBlock Text="{ Binding  Source={StaticResource NumTbVm}, Path=Val.ErrMsgGuiText, UpdateSourceTrigger=PropertyChanged}" Background="{TemplateBinding Background}"/>
<local:Validations x:Key="val" />
<local:NumTbViewModel x:Key="NumTbVm" Val="{StaticResource val}" />
Binding Source not being updated when controls are updated by user (VB.NET Winforms)

Binding Source not being updated when controls are updated by user (VB.NET Winforms)


By : Kairo Arteiro
Date : March 29 2020, 07:55 AM
I wish this helpful for you So after way too long on this, i troubleshot it back to the dataset, the SQL I used to generate the data had many TRIM() functions which causes the column aliasing to be messed up, and most of the columns were set to read only, and the UPDATE comment from the table adapter actually only had a few database columns in it. So removing the TRIM() functions and rebuilding the commands worked, and now it updates as proper.
Using OneWay Binding (to keep DataGrid updated with PropertyChanged) breaks serialization

Using OneWay Binding (to keep DataGrid updated with PropertyChanged) breaks serialization


By : Reinaldo Camargo Fil
Date : March 29 2020, 07:55 AM
hop of those help? I figured it out! (Of course I figure it out myself after hours of googling before posting this)
The issue apparently has something to do with INotifyPropertyChanged. I don't know why it doesn't cause a problem when I don't use the OneWay mode, but what solved it was this:
code :
[field:NonSerialized]
public event PropertyChangedEventHandler PropertyChanged;
Related Posts Related Posts :
  • How to use Addfields in MongoDB C# Aggregation Pipeline
  • MsTest TestCleanup method not called when an unhandled exception is thrown
  • missing last data when exporting gridview to excel
  • How to add array of objects to List in c#
  • Lambda Expression to order (sort) my list collection
  • Library for displaying music notation
  • How to compare two dictionaries in c# and get the output as True and False after validation
  • specify fields to be serialized with JSON
  • How do you obtain the content of a specific node using XmlDocument in C#?
  • How to ignore the first line in a csv file when you read the csv file in C#
  • c# - Problem calling public void from class
  • How to tell a class which objects it should create? Type vs. object confusion :(
  • Save CheckBox state to xml
  • WIX CAQuietExec NETSH Command Fails
  • Issues sending http put request every 60 seconds to RoR app
  • ConfigurationManager.ConnectionStrings.ConnectionString Issue
  • Real size WPF controls for printing
  • How to cancel properly?
  • C# String multiplication error
  • Using Solrnet and Assigning Attributes with Entity Framework Generated POCOs
  • Regex pattern for single backslash
  • TextBox: insert spaces for credit card number?
  • C# DLL loaded for exe-application is not found when launching similar DLL by rundll32.exe
  • Debug a Windows Service with WCF library
  • Open a file from an external assembly?
  • Servicestack RegistrationFeature Unable to bind request
  • Index was outside the bounds of the array confusion
  • Error in Xml to List code. The ':' character, hexadecimal value 0x3A, cannot be included in a name
  • I am trying to do a while loop with a string conditional statement in C#
  • C# 'Cannot access a disposed object. Object name: 'SslStream'.'
  • How to make Gecko use seperate CookieContainer per instance?
  • C# Advanced form "please wait"
  • Send and Receive data C# using network stream
  • How to discover that appsettings changed in C#?
  • Check what needs full trust
  • What is the execution order of an MVC Razor view/layout
  • Table designer (Entity Framework) is too resource intense
  • How to clean up an exception string so it can be displayed via Javascript Alert?
  • Configuring Amazon SES Feedback Notifications via Amazon SNS in ASP.NET MVC (C#)
  • C# api responce and request
  • Dynamodb putitem function not working properly
  • theme in windows phone(light or dark) using c#
  • Backup attached database file(.mdf) using c# and SQL Server
  • What is 'TextFile' and where it is uses in WPF project
  • Using same alias for multiple namespaces
  • how to move mails into separate folders
  • Multithreaded Uploader
  • Memory fragmentation?
  • C# correct exception handling
  • "Could not open macro storage" when accessing using file on another machine
  • How to access other directories of hosted server
  • C# Jagged Array check if value exists/true
  • Why can't I type Clone() properly?
  • exception on accessing dictionary from list
  • Getting the immediate response from server without waiting to 200 message
  • Why am I getting exception Directory Is Not empty?
  • Could not load file or assembly 'CefSharp.dll' or one of its dependencies
  • Sending Email By Using C# in unity3D?
  • Correct usage of await async in webapi
  • Program update code issue
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org