将值绑定到复选框

时间:2010-06-28 09:26:22

标签: c# wpf xaml

我有

class Student
{
public List<Degree> Degrees {get;set;}

}

class Degree
{
public Subject Subject{get;set;}

public int Value {get;set;}
}

class Subject 
{
English =0,
Germany = 1,
Biology=2
}

我有一个Treeview

<HierarchicalDataTemplate DataType="{x:Type MyService:Student}" >
<TextBlock TextAlignment="Justify" VerticalAlignment="Center" Text="English: "/>
<CheckBox IsChecked="{Binding Path=Degrees.Where(d=>d.Subject==English).First()}, Converter={StaticResource degreeToBoolIsPassed}"> </CheckBox>
<TextBlock TextAlignment="Justify" VerticalAlignment="Center" Text="Germany: "/>
<CheckBox IsChecked="{Binding Path=Degrees.Where(d=>d.Subject==Germany).First()}, Converter={StaticResource degreeToBoolIsPassed}"> </CheckBox>
etc

分类的体系结构无法更改,degreeToBoolIsPassed很容易做到,所以我只想要你的xaml,或者这个控件的.cs。 我知道:

<CheckBox IsChecked="{Binding Path=Degrees.Where(d=>d.Subject==Germany).First()}, Converter={StaticResource degreeToBoolIsPassed}"> </CheckBox>

不起作用。这只是我想要的例子。

重要的是:

每位学生必须有4个复选框

1 个答案:

答案 0 :(得分:1)

您需要一个ValueConverter:

Bind to Degrees:

IsChecked="{Binding Path=Degrees, Converter={StaticResource DegreesConverter}, ConverterParameter={x:Static namespace:Subject.Germany}}

在某处实现一个漂亮的转换器:

public class DegreesConverter: IValueConverter
{
    #region IValueConverter Members

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        List<Degree> degrees = (List<Degree>) value;
        return degrees.Any(d => Equals(d.Subject, (Subject)parameter));
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    #endregion
}

将转换器注册在关键DegreesConverter下的某些资源中,如下所示:

<namespace:DegreesConverter x:Key="DegreesConverter" />

请注意,名称空间前缀也应该在您使用此内容的控件中注册,但我想您会知道如何执行此操作!

祝你好运!