ETH官方钱包

前往
大廳
主題

ItemsControl.ItemsSource關聯字串(string)型態資料檢視

Yang | 2022-07-04 12:03:28 | 巴幣 2 | 人氣 312

WPF框架,先記錄簡單資料型態ObservableCollection<string>的關聯方式,較複雜的ObservableCollection<INotifyPropertyChanged>之後補充
以商品的買賣別舉例,將買賣列舉建立到動態資料集(ObservableCollection<string>)內,再與下拉式選單(ComboBox)建立關聯資料檢視

XAML:
<Label Content="買賣別" HorizontalAlignment="Left" Margin="260,10,0,0" VerticalAlignment="Top"/>
<ComboBox x:Name="ComboBoxOrderBuySell" ToolTip="{Binding Path=SelectedValue, RelativeSource={RelativeSource Self}}" HorizontalAlignment="Left" Margin="260,35,0,0" VerticalAlignment="Top" Width="120"/>

C#:
/// <summary>
/// 買賣別
/// </summary>
class OrderBS
{
    enum Enum
    {
        [Description("買")]
        Buy, //0

        [Description("賣")]
        Sell, //1
    }

    static readonly string[] Description =
    {
        Enum.Buy.GetDescription(),
        Enum.Sell.GetDescription(),
    };
}

/// <summary>
/// 取得描述屬性(DescriptionAttribute)
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
static string GetDescription(this Enum obj)
{
    FieldInfo field = obj.GetType().GetField(obj.ToString());
    DescriptionAttribute arr = (DescriptionAttribute)Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute), false);
    return arr.Description;
}

/// <summary>
/// 取得動態資料集的檢視物件
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <returns></returns>
static ICollectionView GetView<T>(this ObservableCollection<T> obj)
{
    CollectionViewSource vs = new CollectionViewSource() { Source = obj, };
    return vs.View;
}

//建立動態資料集,取得資料集的檢視物件,與指定UI建立關聯檢視
static ObservableCollection<T> SetViewAndGetObservation<T>(this ItemsControl obj)
{
    ObservableCollection<T> oc = new ObservableCollection<T>();
    obj.ItemsSource = oc.GetView();
    return oc;
}

//建立動態資料集,取得資料集的檢視物件,與指定UI建立關聯檢視
static ObservableCollection<T> SetViewAndGetObservation<T>(this ItemsControl obj, IEnumerable<T> collection)
{
    ObservableCollection<T> oc = new ObservableCollection<T>(collection);
    obj.ItemsSource = oc.GetView();
    return oc;
}

//ComboBox與買賣列舉建立關聯檢視
ComboBoxOrderBuySell.SetViewAndGetObservation(OrderBS.Description);
ComboBoxOrderBuySell.SelectedIndex = (int)OrderBS.Enum.Buy; //選項給預設值買

繼承ItemsControl的UI都能與動態資料集(ObservableCollection<T>)建立關聯檢視,常見的有
System.Windows.Controls.Menu
System.Windows.Controls.ToolBar
System.Windows.Controls.DataGrid
System.Windows.Controls.ComboBox
System.Windows.Controls.TabControl
System.Windows.Controls.Primitives.StatusBar
System.Windows.Controls.TreeView

之後補充真動態資料ObservableCollection<INotifyPropertyChanged>與DataGrid的範例
送禮物贊助創作者 !
0
留言

創作回應

更多創作