绑定ControlTemplate的Button的内容和命令参数属性

时间:2016-01-28 21:28:36

标签: c# wpf xaml data-binding itemscontrol

好吧,这可能非常简单,我做得不对。我现在正在学习如何使用ItemsControl动态添加项目,如下所示。

<ItemsControl ItemsSource="{Binding Buttons}">
                        <ItemsControl.Template>
                        <ControlTemplate>
                        <Button FontWeight="Bold" Command="{Binding SelectMaterialCommand}" CommandParameter="{Binding CommandParameter}" Width="50" Height="50" Style="{StaticResource RoundedButtonStyle}"  Margin="0,0,0,0" Click="Button_Click_2" Content="{Binding .Content}"></Button>
                        </ControlTemplate>
                        </ItemsControl.Template>
</ItemsControl>

ItemsControl ItemsSource属性绑定到按钮的ObservableCollection。在代码中,我可以创建一个按钮,设置Content和CommandParameter属性并将其添加到ObservableCollection。当我运行应用程序时,会填充一个按钮,但我无法正确绑定Content和CommandParameter属性。

我尝试过几种不同的方法,例如Binding Path=.Binding Path=ContentBinding Path=.Content等,但似乎没有任何效果。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

根据Subramaniam B的建议,我使用了一个位于我的UserControl.Resources部分中的数据模板来实现这一目的。

<DataTemplate x:Key="temp" DataType="{x:Type local:ButtonModel}">
            <telerik:RadButton FontWeight="Bold" FontSize="16" Command="{Binding ButtonCommand}" CommandParameter="{Binding Path=Content}" Width="100" Height="75" Margin="0,0,0,0" MouseLeftButtonUp="Button_Click_2" Content="{Binding Path=Content}">
                <telerik:RadButton.Background>
                    <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                        <GradientStop Color="GhostWhite" Offset="0"/>
                        <GradientStop Color="Gray" Offset="0.5"/>
                        <GradientStop Color="Gray" Offset="0.5"/>
                        <GradientStop Color="GhostWhite" Offset="1"/>
                    </LinearGradientBrush>
                </telerik:RadButton.Background>
            </telerik:RadButton>
        </DataTemplate>

以下是使用模板的地方:

<telerik:RadCarousel Loaded="MaterialCar_Loaded" HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Hidden" x:Name="MaterialCar" Height="200" Background="Blue"  ItemTemplate="{StaticResource temp}" ItemsSource="{Binding Buttons}" Margin="0,0,0,0"/>

答案 1 :(得分:0)

在您的示例中,您将整个ItemsControl(又名:LIST of buttons)的模板设置为A按钮。

无论Buttons集合中有哪些项目,此控件都将呈现为单个按钮。相反,您需要单独保留控件本身的模板,并将I模板用于列表中的项目。

    <ItemsControl ItemsSource="{Binding Buttons}">
        <!-- ItemsControl.Template becomes ItemsControl.ItemTemplate below -->
        <ItemsControl.ItemTemplate> 
            <DataTemplate>
                <Button FontWeight="Bold" Command="{Binding SelectMaterialCommand}" CommandParameter="{Binding CommandParameter}" Width="50" Height="50" Style="{StaticResource RoundedButtonStyle}"  Margin="0,0,0,0" Click="Button_Click_2" Content="{Binding .Content}"></Button>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>