【问题标题】:Databinding in Custom Control自定义控件中的数据绑定
【发布时间】:2011-03-27 15:19:21
【问题描述】:

我正在开发自定义控件。

以下代码是用 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

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

提前致谢

【问题讨论】:

    标签: silverlight data-binding listbox custom-controls


    【解决方案1】:
    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); }
    }
    

    【讨论】:

    • 对不起,我的解释不充分。我试图按 NumValue 排序。忘记 Num 属性。
    • 如果我按照你的说法创建属性,如何从 generic.xaml 访问该属性?
    猜你喜欢
    • 2010-10-11
    • 1970-01-01
    • 2015-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多