自定义控件中的数据绑定

时间:2010-08-10 04:29:45

标签: silverlight data-binding listbox custom-controls

我正在开发自定义控件。

以下代码以generic.xaml

编写
<Style TargetType="local:TwoListBox">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="local:TwoListBox">
                    <StackPanel Orientation="Horizontal">
                        <ListBox x:name="ListBoxForBasic" ItemsSource="{Binding}" DisplayMemberPath="NumValue" Margin="10"/>
                        <ListBox x:name="ListBoxForSorting" ItemsSource="{Binding}" DisplayMemberPath="NumValue" Margin="10"/>
                    </StackPanel>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

这很简单,我有两个ListBox,我试图将以下数据绑定到两个ListBox

public class SampleData
    {
        public int Num { get; set; }
        public int NumValue { get; set; }
    }

    public class SampleDataList : List<SampleData>
    {
        public SampleDataList()
        {
            Add(new SampleData{ Num=1, NumValue=10});
            Add(new SampleData { Num = 2, NumValue = 50 });
            Add(new SampleData { Num = 3, NumValue = 20 });
            Add(new SampleData { Num = 4, NumValue = 40 });
            Add(new SampleData { Num = 5, NumValue = 30 });
        }
    }

在MainPage.xaml中,我使用了TwoListBox自定义控件的示例数据,如下所示:

<local:TwoListBox DataContext="{StaticResource sampleData}"/>

如果按F5,则TwoListBox自定义控件如下所示:

10 10
50 50
20 20
40 40
30 30

但是,我想为第二个ListBox(ListBoxForSorting)绑定排序数据,如下所示:

10 10
50 20
20 30
40 40
30 50

在这种情况下,我该怎么做?

提前致谢

1 个答案:

答案 0 :(得分:0)

public SampleDataList() 
{ 
    Add(new SampleData{ Num=10, NumValue=10}); 
    Add(new SampleData { Num = 20, NumValue = 50 }); 
    Add(new SampleData { Num = 30, NumValue = 20 }); 
    Add(new SampleData { Num = 40, NumValue = 40 }); 
    Add(new SampleData { Num = 50, NumValue = 30 }); 
}

<ListBox x:name="ListBoxForBasic" ItemsSource="{Binding}" DisplayMemberPath="NumValue" Margin="10"/>     
<ListBox x:name="ListBoxForSorting" ItemsSource="{Binding}" DisplayMemberPath="Num" Margin="10"/>  

更新: ItemsSource绑定到IEnumerable,因此您无法通过表达式等设置顺序,因此您必须创建一些属性,如

public SampleDataList GetSortedData() 
{ 
    get { return sampleData.OrderBy(s => s.NumValue); }
}