我正在尝试从代码填充组合框而不是在XAML上定义值。但是,无论我是尝试绑定方法还是从列表中设置它们,我似乎无法让它工作。
使用以下课程
public class Quote
{
public int Value;
public string DisplayValue;
}
以下Observable Collection
public ObservableCollection<Quote> QuoteCollection
{
get
{
return new ObservableCollection<Quote>
{
new Quote{ DisplayValue = "6", Value = 6 },
new Quote{ DisplayValue = "12", Value = 12 },
new Quote{ DisplayValue = "18", Value = 18 },
new Quote{ DisplayValue = "24", Value = 24 },
new Quote{ DisplayValue = "30", Value = 30 },
new Quote{ DisplayValue = "36", Value = 36 },
new Quote{ DisplayValue = "42", Value = 42 },
new Quote{ DisplayValue = "48", Value = 48 },
new Quote{ DisplayValue = "54", Value = 54 },
new Quote{ DisplayValue = "60", Value = 60 }
};
}
}
我似乎无法让它工作,当我这样绑定它时似乎没有任何事情发生:
<local:ExtendedComboBox x:Name="quotes" ItemsSource="{Binding QuoteCollection}" DisplayMemberPath="DisplayValue"/>
当我尝试从像这样的集合List中添加它时:
quotes.ItemsSource = new List<Quote>
{
new Quote{ DisplayValue = "6", Value = 6 },
new Quote{ DisplayValue = "12", Value = 12 },
new Quote{ DisplayValue = "18", Value = 18 },
new Quote{ DisplayValue = "24", Value = 24 },
new Quote{ DisplayValue = "30", Value = 30 },
new Quote{ DisplayValue = "36", Value = 36 },
new Quote{ DisplayValue = "42", Value = 42 },
new Quote{ DisplayValue = "48", Value = 48 },
new Quote{ DisplayValue = "54", Value = 54 },
new Quote{ DisplayValue = "60", Value = 60 }
};
Combobox似乎充满了某些东西,但所有选项都是空白的。
答案 0 :(得分:2)
您的Binding属性是常规属性,但没有getter和setter。所以你需要将你的班级改为以下。
public class Quote
{
public int Value { get; set; }
public string DisplayValue { get; set; }
}
我没有对此进行测试,但应该解决这个问题。
答案 1 :(得分:1)
除了来自AVK的Getter和Setter声明建议之外,您还需要确保已正确设置Page.DataContext。
例如,构造函数方法:
public MainPage()
{
this.InitializeComponent();
this.DataContext = this; //Here
}
收集:
public ObservableCollection<Quote> QuoteCollection
{
get
{
return new ObservableCollection<Quote>
{
new Quote{ DisplayValue = "6", Value = 6 },
new Quote{ DisplayValue = "12", Value = 12 },
new Quote{ DisplayValue = "18", Value = 18 },
new Quote{ DisplayValue = "24", Value = 24 },
new Quote{ DisplayValue = "30", Value = 30 },
new Quote{ DisplayValue = "36", Value = 36 },
new Quote{ DisplayValue = "42", Value = 42 },
new Quote{ DisplayValue = "48", Value = 48 },
new Quote{ DisplayValue = "54", Value = 54 },
new Quote{ DisplayValue = "60", Value = 60 }
};
}
}
自定义类:
public class Quote
{
public int Value { get; set; }
public string DisplayValue { get; set; }
}