문제


I'm asking for help with data binding in C#.
I have several classes:

[Serializable()]
public class Norma 
{
    public BindingList<NormElement> Parameter;
    public Norma()
    {
        Parameter = new BindingList<NormElement>();
    }
    public string Name { get; set; }
}

[Serializable()]
public class NormElement
{
    public decimal M { get; set; }
    public decimal Sigma { get; set; }
}

so, when Norma object N (= new Norma()) comes to form in constructor, i'm doing following:

normBindingSource.DataSource = N;
textBox1.DataBindings.Add("Text", normBindingSource, "Name");

it works!
but when i'm trying to bind like this, it doesn't:

normBindingSource.DataSource = N;
textBox1.DataBindings.Add("Text", normBindingSource, "Name");
textBox2.DataBindings.Add("Text", normBindingSource, "Parameter[0].Sigma");

What am I doing wrong? Before binding, i'm checking that Parameter list is filled with numbers, all ok here. In debug i see that normBindingSource.DataSource is initialized and i can see Parameter field there.

I've tried a lot of options to succeed here, at the beginning Parameter field was just array, but then i've found that it should be with INotifyPropertyChanged, so now i came to this variant.
Thanks in advance!

도움이 되었습니까?

해결책

If you want to bind to the first Sigma Value, as suggested by the parameters[0] binding, best way is to add a property to your Norma class:

public class Norma 
{
    public decimal FirstSigma{get{return Parameters[0].Sigma;}} //add setter if needed
    ....

and bind to that:

textBox2.DataBindings.Add("Text", normBindingSource, "FirstSigma");

If you want to have a separate binding to the parameter list, a separate bindingsource should be created for the list

textBox2.DataBindings.Add("Text", aBindingSourceToParametersList, "Sigma");

다른 팁

Binding only works on properties and you're trying to access a value hidden inside a property inside of an IEnumerable container (which is not supported). What you want to do is extract it into a property to which you can bind it later, like so...

public decimal Sigma
{
    get { return Parameter.Count > 0 ? Parameter[0].Sigma : 0m; }
}

This will return the first signal is you have one or a zero if you don't, which you can then bind using...

textBox2.DataBindings.Add("Text", normBindingSource, "Sigma");
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top