Click here to Skip to main content
15,905,144 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
For my software, I get SQL data and display this.

My XAML with Binding:

<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:Plutus" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" x:Class="Plutus.MainWindow"
    Title="MainWindow" Height="523.725" Width="898" Background="#FF3A3939" WindowStartupLocation="CenterScreen" WindowState="Maximized">
<window.resources>
    
        &lt;Setter Property="Width" Value="35"/>
    

<grid>
    <grid.columndefinitions>
        <ColumnDefinition />
    
    <grid.rowdefinitions>
        <RowDefinition Height="0.03*" />
        <RowDefinition Height="0.04*" />
        <RowDefinition Height="0.04*" />
        <RowDefinition Height="0.88*"/>
        <RowDefinition Height="0.02*" />
    
    
    

    
<ScrollViewer VerticalScrollBarVisibility="Auto" Grid.Row="3" >
    <ItemsControl VerticalAlignment="Top" x:Name="lvDataBinding" HorizontalContentAlignment="Stretch" BorderThickness="0" Margin="10" Grid.Row="3" Background="{x:Null}" ItemsSource="{Binding}" Foreground="White">
        <itemscontrol.itemtemplate>
            <DataTemplate DataType="{x:Type local:CL_Operation}">
                <Border BorderBrush="White" BorderThickness="1" CornerRadius="3" Margin="0,3" Grid.ColumnSpan="0" Background="Transparent" HorizontalAlignment="Left" VerticalAlignment="Top">
                    <Grid Width="{Binding strWidth}" Height="60" Background="Transparent" Margin="0,1">
                        <grid.columndefinitions>
                                <ColumnDefinition Width="0.06*" />
                                <ColumnDefinition Width="0.09*" />
                                <ColumnDefinition Width="0.1*" />
                                <ColumnDefinition Width="0.12*" />
                                <ColumnDefinition Width="0.1*" />
                                <ColumnDefinition Width="0.1*" />
                                <ColumnDefinition Width="0.1*" />
                                <ColumnDefinition Width="0.05*" />
                                <ColumnDefinition Width="0.05*" />
                                <ColumnDefinition Width="0.05*" />
                                <ColumnDefinition Width="0.05*" />
                                <ColumnDefinition Width="0.03*" />
                            
                        <grid.rowdefinitions>
                            <RowDefinition />
                            <RowDefinition />
                            <RowDefinition />
                        
                            <UniformGrid Tag="{Binding strRueck}"  Grid.Column="0" Grid.Row="0" Grid.RowSpan="2" MouseLeftButtonUp="Test" >
                                <uniformgrid.style>
                                    
                                        <Style.Triggers>
                                            &lt;Trigger Property="IsMouseOver" Value="true">
                                                &lt;Setter Property="Background" Value="White"/>
                                            </trigger>
                                            &lt;Trigger Property="IsMouseOver" Value="false">
                                                &lt;Setter Property="Background" Value="{Binding scbBackColor}"/>
                                            </trigger>
                                        </style.Triggers>
                                    
                                
                                <TextBlock Text="{Binding strPriorite}" FontSize="36" Foreground="Red" HorizontalAlignment="Center" VerticalAlignment="Center" FontWeight="Bold"/>
                        
                            <UniformGrid  Grid.Column="0" Grid.Row="2"  Background="{Binding scbBackColor}" MouseLeftButtonUp="Test" >
                                <TextBlock Text="{Binding strSsSect}" FontSize="14" Foreground="Black" HorizontalAlignment="Right" VerticalAlignment="Bottom" FontWeight="Bold" />
                            
                            <UniformGrid  Grid.Column="1" Grid.Row="0" Grid.RowSpan="3">
                            <TextBlock Text="{Binding strRetardAvanceText}" FontSize="28" Foreground="{Binding scbColorRetardAvance}" FontWeight="Bold" HorizontalAlignment="Center" VerticalAlignment="Center" />
                        
                        <UniformGrid  Grid.Column="2" Grid.Row="0" Grid.ColumnSpan="2" Grid.RowSpan="2">
                            <uniformgrid.style>
                                
                                    <Style.Triggers>
                                        &lt;Trigger Property="IsMouseOver" Value="true">
                                            &lt;Setter Property="Background" Value="Gray"/>
                                        </trigger>
                                    </style.Triggers>
                                
                            
                                <TextBlock Tag="{Binding strRueck}" Foreground="{Binding scbColorNumOfOp}" Text="{Binding strNoOfOp}" FontSize="26" FontWeight="Bold" MouseLeftButtonUp="Test"/>
                        
                        <UniformGrid  Grid.Column="2" Grid.Row="2" Grid.ColumnSpan="3">
                            <TextBlock Text="{Binding strDescriptionOp}" FontSize="14" Foreground="White"/>
                        
                        <UniformGrid Grid.Column="4" Grid.Row="0">
                            <TextBlock Text="{Binding strNoArticle}" FontSize="14" Foreground="White"/>
                        
                        <UniformGrid  Grid.Column="4" Grid.Row="1">
                            <TextBlock Text="{Binding strDateFormatee}" FontSize="14" Foreground="White"/>
                        
                        <UniformGrid Grid.Column="5" Grid.Row="0">
                            <TextBlock Text="{Binding strPcesPoste}" FontSize="14" Foreground="White"/>
                        
                        <UniformGrid  Grid.Column="5" Grid.Row="1">
                            <TextBlock Text="{Binding strTpsPoste}" FontSize="14" Foreground="White"/>
                        
                        <UniformGrid  Grid.Column="6" Grid.Row="0">
                            <TextBlock Text="{Binding strTempsPoste}" FontSize="14" Foreground="White"/>
                        
                        <UniformGrid  Grid.Column="6" Grid.Row="1">
                            <TextBlock Text="{Binding strClient}" FontSize="14" Foreground="White"/>
                        
                        <UniformGrid  Grid.Column="5" Grid.Row="2" Grid.ColumnSpan="3">
                            <TextBlock Text="{Binding strTypeOp}" FontSize="14" Foreground="White"/>
                        
                            <UniformGrid  Grid.Column="9" Grid.Row="3">
                                <TextBlock Text="{Binding strAuart}" FontSize="12" Foreground="White" FontWeight="Bold"/>
                            
                        
                
            
        
        <itemscontrol.itemspanel>
            <itemspaneltemplate>
                <UniformGrid Columns="2"/>


My C# code: in my boucle for I sum quantity, and I need to display this result in my label XAML

C#
public partial class MainWindow : Window
{
    public ObservableCollection<cl_operation> lstOperationsTemp = new ObservableCollection<cl_operation>();

    public List<string> lstSelectedLignesChoisi = new List<string>();
    public List<string> lstSelectedIlotsChoisi = new List<string>();
    public List<string> lstPostesTravailChoisi = new List<string>();


    DispatcherTimer dtTimer = new DispatcherTimer();

    DataTable dtOps = new DataTable();
    DataView dvOps = new DataView();

    Thread thrGetList;

    string connectionString = "Data Source=SERVER\\INSTANCE;Initial Catalog=DB;Integrated Security=True";
    string strOrderBy;
    string strResultTri;
    string strWhere;
    string strWhereLigne;
    string strWhereIlot;
    string strWherePosteTravail;

    int iTimer = 30;

    public MainWindow()
    {
        InitializeComponent();

        dtTimer.Tick += new EventHandler(timer_Tick);
        dtTimer.Interval = new TimeSpan(0, 0, 1);
        //dtTimer.Start();

        thrGetList = new Thread(GetList);
        thrGetList.Start();
    }

    public CL_Operation clOp { get; set; }

    public void GetList()
    {
        dvOps = dtOps.DefaultView;

        Application.Current.Dispatcher.Invoke(new Action(() => lstOperationsTemp.Clear()));
        dtOps.Clear();

        string strQueryDatas;

        SqlConnection con = new SqlConnection(connectionString);

        strQueryDatas = "SELECT * FROM [DB].[dbo].[VIEW] " + strWhere + " " + strOrderBy;

        SqlDataAdapter adOps = new SqlDataAdapter(strQueryDatas, con);

        adOps.Dispose();

        try
        {
            con.Open();
            SqlCommand sqlCmd = new SqlCommand(strQueryDatas, con);
            sqlCmd.CommandTimeout = 500;
            adOps.SelectCommand = sqlCmd;
            adOps.Fill(dtOps);
            adOps.Dispose();
            sqlCmd.Dispose();
            con.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

        DateTime dtNow = DateTime.Now;

        double dblTotalQte = 0;
        double dblTotalOp = 0;
        double dblTotalTemps=0;

        for (int i = 0; i < dvOps.Count; i++)
        {
            clOp = new CL_Operation();

            clOp.strWidth = Convert.ToString(Convert.ToInt32(System.Windows.SystemParameters.PrimaryScreenWidth) / 2);

            clOp.strNoOfOp = dvOps[i]["NumOF"].ToString().Trim() + " - " + dvOps[i]["NumOP"].ToString().Trim();
            clOp.strAuart = dvOps[i]["AUART"].ToString().Trim();
            clOp.strMaufnr = dvOps[i]["MAUFNR"].ToString().Trim();
            clOp.strCodeLigne = dvOps[i]["CodeLigne"].ToString().Trim();
            //clOp.strNumOp = dvOps[i]["NumOP"].ToString().Trim();
            clOp.strRueck = dvOps[i]["RUECK"].ToString().Trim();
            clOp.strDescriptionOp = dvOps[i]["DesOpe"].ToString().Trim();
            clOp.strNoArticle = dvOps[i]["NumArt"].ToString().Trim();
            clOp.strDateFormatee = dvOps[i]["DateFormatee"].ToString().Trim();
            clOp.strPcesPoste = Convert.ToString(Convert.ToDouble(String.Format("{0:0}", dvOps[i]["QtePoste"].ToString().Trim()))) + " pces";
            clOp.strTpsPoste = Convert.ToString(Convert.ToDouble(String.Format("{0:0.00}", dvOps[i]["TpsChargePoste"].ToString()))) + " Hrs";
            clOp.strClient = dvOps[i]["NomClientCourt"].ToString().Trim();
            clOp.strTypeOp = dvOps[i]["MAKTX"].ToString();
            clOp.strPriorite = dvOps[i]["PriorOF"].ToString();
            clOp.strSsSect = dvOps[i]["SsSect"].ToString();
            clOp.strDateDerBadge = Convert.ToDateTime(dvOps[i]["DatDerBadg"]);

            // Here i sum my quantity
            dblTotalQte += Convert.ToDouble(dvOps[i]["QtePoste"].ToString().Trim());
            dblTotalTemps += Convert.ToDouble(dvOps[i]["TpsChargePoste"].ToString().Trim());
            dblTotalOp++;

            // I need to display this result in my label
            clOp.strTotaux = "Nb OPs : " + dblTotalOp.ToString() + " Qte totale : " + dblTotalQte.ToString() + " Pces Temps total : " + dblTotalTemps + " Hrs";

            Application.Current.Dispatcher.Invoke(new Action(() => lstOperationsTemp.Add(clOp)));

            DateTime dtRetard = Convert.ToDateTime(clOp.strDateFormatee);
            DateTime dtTempsPoste = Convert.ToDateTime(clOp.strDateDerBadge);
            TimeSpan tRetard = dtNow.Date - dtRetard.Date;
            TimeSpan tTempsPoste = dtNow - dtTempsPoste;

            clOp.strRetardAvanceText = Convert.ToString(Math.Abs(Convert.ToDouble(tRetard.TotalDays))) + " jrs";

            clOp.scbBackColor.Freeze();
            clOp.scbColorRetardAvance.Freeze();

        }

        ObservableCollection<cl_operation> lstOperations = new ObservableCollection<cl_operation>(lstOperationsTemp);

        Application.Current.Dispatcher.Invoke(new Action(() => this.DataContext = lstOperations));

    }

    private void Test(object sender, MouseButtonEventArgs e)
    {
        string str = ((TextBlock)sender).Tag.ToString();

        MessageBox.Show(str);

        foreach (var item in lstOperationsTemp)
        {
            if (item.strRueck == str)
            {
                MessageBox.Show(item.strNoOfOp);
                break;
            }
        }
    }

}


And my class (ClassStructure.cs):

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data;
using System.Data.SqlClient;

namespace Project
{
    public class CL_Operation
    {
        public string strWidth { get; set; }
        public string strAuart { get; set; }
        public string strMaufnr { get; set; }
        public string strNoOfOp { get; set; }
        public string strRueck { get; set; }
        public string strCodeLigne { get; set; }
        public string strNumOp { get; set; }
        public string strDescriptionOp { get; set; }
        public string strNoArticle { get; set; }
        public string strDateFormatee { get; set; }
        public string strPcesPoste { get; set; }
        public string strTpsPoste { get; set; }
        public string strClient { get; set; }
        public string strTypeOp { get; set; }
        public string strPriorite { get; set; }
        public string strPoste { get; set; }
        public string strSsSect { get; set; }
        public string strTotaux { get; set; }
        public DateTime strDateDerBadge { get; set; }
        public string strTempsPoste { get; set; }
        public string strRetardAvanceText { get; set; }
        public SolidColorBrush scbColorNumOfOp { get; set; }
        public SolidColorBrush scbColorRetardAvance { get; set; }
        public SolidColorBrush scbBackColor { get; set; }
    }

}


In this class, I created a public string strTotaux.

I need to display this variable in my label (XAML).

It's work, my result it's display, but it's the result of my registre[0] of my class clOp, but I need the total..

What I have tried:

I have try with strTotaux, clop.StrTotaux...
Posted
Updated 20-Sep-17 22:37pm
v2
Comments
Graeme_Grant 20-Sep-17 3:42am    
You need to repost as this is too poorly formatted and missing bits. The editor has a code dropdown for allocating types of blocks of code. Use these for formatting.

Please update the question with clear and concise details, sample code, any error messages (including inner exception details), etc, by clicking on the Improve question widget.
Steve15f 20-Sep-17 5:06am    
Hello
Ok, i can try, my english is very bad.
Graeme_Grant 20-Sep-17 17:26pm    
Sorry, I don't understand. What field is the SUM and where in XAML is the sum supposed to appear?

You are binding to a collection of objects. Can you see the data in the view? I ask as you are using binding with an ObservableCollection however your class is not implementing the INotifyPropertyChanged[^]. INotifyPropertyChanged is required if you are setting values in your class object. Without it, the binding system will not see any changes.

You will need to do something like this:

1. Base class for INotifyPropertyChanged
C#
public abstract class ObservableBase : INotifyPropertyChanged
{
    public void Set<TValue>(ref TValue field, TValue newValue, [CallerMemberName] string propertyName = "")
    {
        if (EqualityComparer<TValue>.Default.Equals(field, default(TValue)) || !field.Equals(newValue))
        {
            field = newValue;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

And the re-worked Class:
C#
public class CL_Operation : ObservableBase
{
    private string _strWidth;
    public string strWidth
    {
        get => _strWidth;
        set => Set(ref _strWidth, value);
    }
        
    private string _strAuart;
    public string strAuart
    {
        get => _strAuart;
        set => Set(ref _strAuart, value);
    }

    private string _strMaufnr;
    public string strMaufnr
    {
        get => _strMaufnr;
        set => Set(ref _strMaufnr, value);
    }

    private string _strNoOfOp;
    public string strNoOfOp
    {
        get => _strNoOfOp;
        set => Set(ref _strNoOfOp, value);
    }

    private string _strRueck;
    public string strRueck
    {
        get => _strRueck;
        set => Set(ref _strRueck, value);
    }

    private string _strCodeLigne;
    public string strCodeLigne
    {
        get => _strCodeLigne;
        set => Set(ref _strCodeLigne, value);
    }

    private string _strNumOp;
    public string strNumOp
    {
        get => _strNumOp;
        set => Set(ref _strNumOp, value);
    }

    private string _strDescriptionOp;
    public string strDescriptionOp
    {
        get => _strDescriptionOp;
        set => Set(ref _strDescriptionOp, value);
    }

    private string _strNoArticle;
    public string strNoArticle
    {
        get => _strNoArticle;
        set => Set(ref _strNoArticle, value);
    }

    private string _strDateFormatee;
    public string strDateFormatee
    {
        get => _strDateFormatee;
        set => Set(ref _strDateFormatee, value);
    }

    private string _strPcesPoste;
    public string strPcesPoste
    {
        get => _strPcesPoste;
        set => Set(ref _strPcesPoste, value);
    }

    private string _strTpsPoste;
    public string strTpsPoste
    {
        get => _strTpsPoste;
        set => Set(ref _strTpsPoste, value);
    }

    private string _strClient;
    public string strClient
    {
        get => _strClient;
        set => Set(ref _strClient, value);
    }

    private string _strTypeOp;
    public string strTypeOp
    {
        get => _strTypeOp;
        set => Set(ref _strTypeOp, value);
    }

    private string _strPriorite;
    public string strPriorite
    {
        get => _strPriorite;
        set => Set(ref _strPriorite, value);
    }

    private string _strPoste;
    public string strPoste
    {
        get => _strPoste;
        set => Set(ref _strPoste, value);
    }

    private string _strSsSect;
    public string strSsSect
    {
        get => _strSsSect;
        set => Set(ref _strSsSect, value);
    }

    private string _strTotaux;
    public string strTotaux
    {
        get => _strTotaux;
        set => Set(ref _strTotaux, value);
    }

    private DateTime _strDateDerBadge;
    public DateTime strDateDerBadge
    {
        get => _strDateDerBadge;
        set => Set(ref _strDateDerBadge, value);
    }

    private string _strTempsPoste;
    public string strTempsPoste
    {
        get => _strTempsPoste;
        set => Set(ref _strTempsPoste, value);
    }

    private string _strRetardAvanceText;
    public string strRetardAvanceText
    {
        get => _strRetardAvanceText;
        set => Set(ref _strRetardAvanceText, value);
    }

    private SolidColorBrush _scbColorNumOfOp;
    public SolidColorBrush scbColorNumOfOp
    {
        get => _scbColorNumOfOp;
        set => Set(ref _scbColorNumOfOp, value);
    }

    private SolidColorBrush _scbColorRetardAvance;
    public SolidColorBrush scbColorRetardAvance
    {
        get => _scbColorRetardAvance;
        set => Set(ref _scbColorRetardAvance, value);
    }

    private SolidColorBrush _scbBackColor;
    public SolidColorBrush scbBackColor
    {
        get => _scbBackColor;
        set => Set(ref _scbBackColor, value);
    }
}

Update: Older C# Syntax:
C#
public abstract class ObservableBase : INotifyPropertyChanged
{
    public void Set<TValue>(ref TValue field, TValue newValue, [CallerMemberName] string propertyName = "")
    {
        if (EqualityComparer<TValue>.Default.Equals(field, default(TValue)) || !field.Equals(newValue))
        {
            field = newValue;
			if (PropertyChanged != null)
			{
				PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
			}
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

public class CL_Operation : ObservableBase
{
	private string _strWidth;
	public string strWidth
	{
		get { return _strWidth; }
		set { Set(ref _strWidth, value); }
	}

    private string _strAuart;
    public string strAuart
    {
        get
        {
            return _strAuart;
        }

        set
        {
            Set(ref _strAuart, value);
        }
    }

    private string _strMaufnr;
    public string strMaufnr
    {
        get
        {
            return _strMaufnr;
        }

        set
        {
            Set(ref _strMaufnr, value);
        }
    }

    private string _strNoOfOp;
    public string strNoOfOp
    {
        get
        {
            return _strNoOfOp;
        }

        set
        {
            Set(ref _strNoOfOp, value);
        }
    }

    private string _strRueck;
    public string strRueck
    {
        get
        {
            return _strRueck;
        }

        set
        {
            Set(ref _strRueck, value);
        }
    }

    private string _strCodeLigne;
    public string strCodeLigne
    {
        get
        {
            return _strCodeLigne;
        }

        set
        {
            Set(ref _strCodeLigne, value);
        }
    }

    private string _strNumOp;
    public string strNumOp
    {
        get
        {
            return _strNumOp;
        }

        set
        {
            Set(ref _strNumOp, value);
        }
    }

    private string _strDescriptionOp;
    public string strDescriptionOp
    {
        get
        {
            return _strDescriptionOp;
        }

        set
        {
            Set(ref _strDescriptionOp, value);
        }
    }

    private string _strNoArticle;
    public string strNoArticle
    {
        get
        {
            return _strNoArticle;
        }

        set
        {
            Set(ref _strNoArticle, value);
        }
    }

    private string _strDateFormatee;
    public string strDateFormatee
    {
        get
        {
            return _strDateFormatee;
        }

        set
        {
            Set(ref _strDateFormatee, value);
        }
    }

    private string _strPcesPoste;
    public string strPcesPoste
    {
        get
        {
            return _strPcesPoste;
        }

        set
        {
            Set(ref _strPcesPoste, value);
        }
    }

    private string _strTpsPoste;
    public string strTpsPoste
    {
        get
        {
            return _strTpsPoste;
        }

        set
        {
            Set(ref _strTpsPoste, value);
        }
    }

    private string _strClient;
    public string strClient
    {
        get
        {
            return _strClient;
        }

        set
        {
            Set(ref _strClient, value);
        }
    }

    private string _strTypeOp;
    public string strTypeOp
    {
        get
        {
            return _strTypeOp;
        }

        set
        {
            Set(ref _strTypeOp, value);
        }
    }

    private string _strPriorite;
    public string strPriorite
    {
        get
        {
            return _strPriorite;
        }

        set
        {
            Set(ref _strPriorite, value);
        }
    }

    private string _strPoste;
    public string strPoste
    {
        get
        {
            return _strPoste;
        }

        set
        {
            Set(ref _strPoste, value);
        }
    }

    private string _strSsSect;
    public string strSsSect
    {
        get
        {
            return _strSsSect;
        }

        set
        {
            Set(ref _strSsSect, value);
        }
    }

    private string _strTotaux;
    public string strTotaux
    {
        get
        {
            return _strTotaux;
        }

        set
        {
            Set(ref _strTotaux, value);
        }
    }

    private DateTime _strDateDerBadge;
    public DateTime strDateDerBadge
    {
        get
        {
            return _strDateDerBadge;
        }

        set
        {
            Set(ref _strDateDerBadge, value);
        }
    }

    private string _strTempsPoste;
    public string strTempsPoste
    {
        get
        {
            return _strTempsPoste;
        }

        set
        {
            Set(ref _strTempsPoste, value);
        }
    }

    private string _strRetardAvanceText;
    public string strRetardAvanceText
    {
        get
        {
            return _strRetardAvanceText;
        }

        set
        {
            Set(ref _strRetardAvanceText, value);
        }
    }

    private SolidColorBrush _scbColorNumOfOp;
    public SolidColorBrush scbColorNumOfOp
    {
        get
        {
            return _scbColorNumOfOp;
        }

        set
        {
            Set(ref _scbColorNumOfOp, value);
        }
    }

    private SolidColorBrush _scbColorRetardAvance;
    public SolidColorBrush scbColorRetardAvance
    {
        get
        {
            return _scbColorRetardAvance;
        }

        set
        {
            Set(ref _scbColorRetardAvance, value);
        }
    }

    private SolidColorBrush _scbBackColor;
    public SolidColorBrush scbBackColor
    {
        get
        {
            return _scbBackColor;
        }

        set
        {
            Set(ref _scbBackColor, value);
        }
    }
}

UPDATE #2: Here is an example of simple binding using the above ObservableBase class. Many others are on the internet...
C#
public class PersonModel : ObservableBase
{
    private string name;
    public string Name
    {
        get { return name; }
        set { Set(ref name, value); }
    }

    private int age;
    public int Age
    {
        get { return age; }
        set { Set(ref age, value); }
    }
}

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = this;
        Mock();
    }

    public ObservableCollection<PersonModel> Persons { get; set; }
        = new ObservableCollection<PersonModel>();

    private Random rand = new Random();

    private void Mock()
    {
        for (int i = 0; i < 10; i++)
        {
            Persons.Add(new PersonModel
            {
                Name = string.Format("Person {0}", i),
                Age = rand.Next(20, 50)
            });
        }
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        foreach (var person in Persons)
        {
            person.Age = rand.Next(20, 50);
        }
    }
}

And the page:
XML
<Window
    x:Class="WpfSimpleBinding.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    mc:Ignorable="d"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

    xmlns:local="clr-namespace:WpfSimpleBinding"

    Title="Basic code-behin binding example"
    WindowStartupLocation="CenterScreen" Height="400" Width="300">

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition />
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>

        <Grid.Resources>
            <DataTemplate DataType="{x:Type local:PersonModel}">
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition/>
                        <ColumnDefinition Width="Auto"/>
                    </Grid.ColumnDefinitions>
                    <TextBlock Text="{Binding Name}" Margin="10 3"/>
                    <TextBlock Text="{Binding Age}" Margin="10 3"
                               Grid.Column="1"/>
                </Grid>
            </DataTemplate>
        </Grid.Resources>

        <ListBox ItemsSource="{Binding Persons}">
            <ListBox.ItemContainerStyle>
                <Style TargetType="ListBoxItem">
                    <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
                </Style>
            </ListBox.ItemContainerStyle>
        </ListBox>
        <Button Content="Randomize" Padding="10 5" Margin="10"
                HorizontalAlignment="Center" VerticalAlignment="Center"
                Grid.Row="1" Click="Button_Click"/>
    </Grid>

</Window>

Click the button and watch the information (age) update using the binding system.
 
Share this answer
 
v4
Comments
Steve15f 21-Sep-17 0:58am    
Hello

Thank you for your reply

I have error on :

PropertyChanged?.Invoke :

Invalid expression term '.'
only an assignment, call, increment, decrement, expectation, and new object expressions can be used as a statement
the name 'Invoke' does not exist in the current context
Syntax error, ':' expected

In my classe i have an error :

get => _strWidth; : error on "=>" : { or ; excepted

Thank you very much in advance.
Graeme_Grant 21-Sep-17 1:03am    
If you look at my answer, I have used it here:
public class CL_Operation : ObservableBase
Steve15f 21-Sep-17 1:07am    
Hello, yes, it's work :

public class CL_Operation : ObservableBase is ok.

I have an error on

PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); and on

get => _strRetardAvanceText;

Thank you very much, very much very much
Graeme_Grant 21-Sep-17 1:17am    
I'm using modern C# syntax.
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));

is equivalent to the older:
if (PropertyChanged != null)
{
    PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

and for properties:
private string _strWidth;
public string strWidth
{
    get => _strWidth;
    set => Set(ref _strWidth, value);
}

is equivalent to the older:
private string _strWidth;
public string strWidth
{
    get { return _strWidth; }
    set { Set(ref _strWidth, value); }
}

I'll update the answer with older syntax.
Steve15f 21-Sep-17 1:26am    
Hello

Thank you very much for your reply.

But, i don't understand, why the new syntax do not work ? With the old syntax it's ok.

I'm using Visual Sutdio 2012, it's the reason ?

For my problem : i see my data in the view, before it's worked too.

With your code, it's fastly than with my code.

But my problem is not solved.

In my label in XAML with my binding strTotaux, it's always the registre [0] to display of my classe CL_Operation, but nut the sum

I calculate the sum in my for loop :

dblTotalQte += Convert.ToDouble(dvOps[i]["QtePoste"].ToString().Trim());
dblTotalTemps += Convert.ToDouble(dvOps[i]["TpsChargePoste"].ToString().Trim());
dblTotalOp++;


clOp.strTotaux = "Nb OPs : " + dblTotalOp.ToString() + " Qte totale : " + dblTotalQte.ToString() + " Pces Temps total : " + dblTotalTemps + " Hrs";

Thank you.
How !

It's work ! Thank you very much Graeme_Grant

I moved

private string _strTotaux;
public string strTotaux
{
get { return _strTotaux; }
set { _strTotaux = value; }
}

In my MainWindow

Thank you
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900