开发者

WPF ListView ItemTemplate questions

开发者 https://www.devze.com 2022-12-13 18:18 出处:网络
Let\'s say that I\'ve got the following class hierarchy : public static class Constants { public enum MyEnum

Let's say that I've got the following class hierarchy :

public static class Constants
{
    public enum MyEnum
    {
       Value1 =0,
       Value2,
       Value3
    }
}

public class Data : INotifyPropertyChanged
{
    public Data(string name, ushort id, Constants.MyEnum e)
    {
        DataName = name;
        DataId = id;
        DataEnum = e;
    }

    #region Properties
    // get / set implementation not shown
    public string DataName;
    public ushort DataId;
    public Constants.MyEnum DataEnum;
    #endregion

    // INotifyPropertyChanged implementation not shown
    // Fields implementation not shown
}

public class DataContainer
{
    public DataContainer()
    {
        ContainedData = new ObservableCollection<Data>();
        ContainedData.Add(new Data("data1", 1, Constants.MyEnum.Value1));
        ContainedData.Add(new Data("data2", 2, Constants.MyEnum.Value2));
        ContainedData.Add(new Data("data3", 3, Constants.MyEnum.Value3));
    }

    public ObservableCollection<Data> ContainedData;
}

I'd l开发者_如何学JAVAike to databind DataContainer's ContainedData to a ListView and create an ItemTemplate containing :

My goals :

  1. I want the Combobox to be able to display all possible MyEnum values
  2. I want the Combobox to implement a TwoWay binding to the DataEnum field

Questions :

  1. How do I achieve the goals listed ?
  2. Data's properties are of varying types. Does that matter for the TextBox? If so, should I expose them as strings only? How do I validate the data ? (ie make sure that a user doesn't pass "abc" in the DataId field etc. )


For getting the MyEnum values into an ItemsControl such as a ComboBox, see http://blogs.msdn.com/wpfsdk/archive/2007/02/22/displaying-enum-values-using-data-binding.aspx. To display this in a DataTemplate within a ListView you will use the CellTemplate property:

<DataTemplate x:Key="DataEnumTemplate">
  <ComboBox ItemsSource="..." SelectedItem="{Binding DataEnum, Mode=TwoWay}" />
</DataTemplate>

<GridViewColumn CellTemplate="{StaticResource DataEnumTemplate" />

(where the ItemsSource is per the linked article).

Re data types, a TextBox.Text binding will automatically convert between the text string and the ushort or whatever, and will automatically signal a validation error if the string is not convertible (e.g. "abc").

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号