![](/img/trans.png)
[英]How do I create a user control with 3 combo boxes and a different data binding for each?
[英]How can I use data binding in WPF to create a new user control for each element in a list?
我有一個對象列表。 對於列表中的每個項目,我想創建一個綁定到該項目的新用戶控件。 根據我的閱讀,以編程方式執行此操作是WPF的不良做法(並且不太直接),因此我應該使用數據綁定作為解決方案。 問題是,我無法弄清楚如何做到這一點。 我在編譯時不知道列表的內容(只是類型),所以我無法為每個元素創建和綁定XAML。 谷歌和MSDN似乎沒有任何答案,所以也許我正在考慮這個錯誤的方式? 我需要做什么?
謝謝
編輯:澄清一下,我正在嘗試制作自己的音樂評分軟件,比如Rosegarden。 該列表將包含所有度量,用戶控件將是它們的可視化表示。
比Julien Lebosquain的建議更通用的方法(以及當項目列表包含多種數據類型的對象時將起作用的方法):
創建一個DataTemplate
,用於顯示列表中的類型項,例如:
<DataTemplate DataType="local:Measure">
<local:MeasureUserControl DataContext="{Binding}"/>
</DataTemplate>
使用ItemsControl
來顯示項目:
<ItemsControl ItemsSource="{Binding MeasureList}"/>
您可以設置ItemsPanel
的財產ItemsControl
到ItemsPanelTemplate
執政將如何布局的用戶控件,例如:
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
這種方式一般最好使用一個ListBox
,當你不希望的功能ListBox
,例如它的默認邊框和選擇行為。
您可以使用具有自定義項樣式的標准ListBox
:
在資源的某個地方:
<Style TargetType="{x:Type ListBoxItem}" x:Key="CustomItemStyle">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<yourns:YourControl />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
在你的窗口/頁面/ usercontrol中:
<ListBox ItemsSource="{Binding ...}" ItemContainerStyle="{StaticResource CustomItemStyle}" />
由於您的對象將綁定到列表框,因此將為每個對象創建一個隱式ListBoxItem
,並將其DataContext
設置為該對象,以便您可以在YourControl
使用綁定而不必擔心。
所有上述答案都有效,但我將離開我在申請中的表現。 我正在實現利用這些WPF功能的MVVM架構。 這是我正在使用的UserControl
,其中有一個ItemsControl
填充了某種類型的項目:
<UserControl x:Class="Controls.StepView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:my="clr-namespace:Controls"
Background="Transparent">
<UserControl.Resources>
<DataTemplate DataType="{x:Type my:ParameterViewModel}" >
<my:ParameterView HorizontalAlignment="Stretch" Margin="25 0 0 0"/>
</DataTemplate>
</UserControl.Resources>
<Grid>
<ItemsControl Name="stkStepContent" ItemsSource="{Binding Parameters}" />
</Grid>
</UserControl>
讓我為您解釋代碼。 在DataTemplate
部分中,我說我想使用UserControl
ParameterView呈現類ParameterViewModel的對象。 ItemsControl
的ItemsSource
屬性綁定到List<ParameterViewModel>
。 當為List上的每個ParameterViewModel啟動ItemsControl
,它將創建一個ParameterView並將其DataContext設置為它正在呈現的ParameterViewmodel。 我發現這種架構模式對我來說是最直觀的構建WPF應用程序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.