C#WPF使用与sum的绑定 [英] C# WPF use binding with sum

查看:113
本文介绍了C#WPF使用与sum的绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我的软件,我获取SQL数据并显示它。



我的XAML绑定:



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"/>





我的C#代码:在我的账户里,我总和数量,我需要在我的标签XAML中显示这个结果





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

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;
            }
        }
    }

}





我的班级(ClassStructure.cs):





And my class (ClassStructure.cs):

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; }
    }

}





在这堂课中,我创建了一个公共字符串strTotaux。 br />


我需要在我的标签(XAML)中显示这个变量。



这是工作,我的结果是显示,但这是我的课程clOp的注册[0]的结果,但我需要总数...



我尝试了什么:



我试过strTotaux,clop.StrTotaux ...



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...

推荐答案

你有约束力到一组对象。你能看到视图中的数据吗?我问你正在使用与ObservableCollection的绑定,但是你的类没有实现 INotifyPropertyChanged [ ^ ]。如果要在类对象中设置值,则需要 INotifyPropertyChanged 。没有它,绑定系统将不会看到任何变化。



你需要做这样的事情:



1. 的基类INotifyPropertyChanged

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
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:

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);
    }
}



更新:旧版C#语法:


Update: Older C# Syntax:

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...


UPDATE #2: Here is an example of simple binding using the above ObservableBase class. Many others are on the internet...

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:


And the page:

<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.


Click the button and watch the information (age) update using the binding system.


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
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


这篇关于C#WPF使用与sum的绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆