How to manually bind static Items to SplitButton (mahapps) via XAML

江枫思渺然 提交于 2019-12-24 00:34:43

问题


How do i manually add for example 2 items (buttons) from which the first is preselected via xaml? Like:

<controls:SplitButton SelectedIndex="0">
    <controls:SplitButton.Items>
        <Button Content="Button 1"/>
        <Button Content="Button 2"/>
    </controls:SplitButton.Items>
</controls:SplitButton>

Documentation tells me to use ItemsSource Binding but there is no example of the code behind.


回答1:


This is the XAML:

<controls:SplitButton x:Name="splitButton" 
        SelectedIndex="1" 
        HorizontalAlignment="Left" 
        VerticalAlignment="Top" 
        Grid.Column="1">
    <controls:SplitButton.ItemTemplate>
        <DataTemplate>
            <Grid>
                <TextBlock HorizontalAlignment="Left" 
                        TextWrapping="Wrap" 
                        Text="{Binding Text}" 
                        VerticalAlignment="Top"/>
            </Grid>
        </DataTemplate>
    </controls:SplitButton.ItemTemplate>
</controls:SplitButton>

This is the code behind:

class SplitButtonItem
{
    public string Text { get; set; }
}

public MainWindow()
{
    InitializeComponent();

    var button1 = new SplitButtonItem() { Text = "Item 01", };
    var button2 = new SplitButtonItem() { Text = "Item 02", };
    var buttonList = new List<SplitButtonItem>() 
    {
        button1, 
        button2,
    };
    splitButton.ItemsSource = buttonList;
}

This is how it look at runtime:

Is this what you're looking for?




回答2:


You can use the ItemsSource and an enumerable and don't specify a DisplayMemberPath.

<controls:SplitButton HorizontalContentAlignment="Left"
                        HorizontalAlignment="Center"
                        VerticalContentAlignment="Center"
                        Width="120"
                        VerticalAlignment="Top">
    <controls:SplitButton.ItemsSource>
        <x:Array Type="system:String">
            <system:String>Label 1</system:String>
            <system:String>Another one</system:String>
            <system:String>Works now</system:String>
        </x:Array>
    </controls:SplitButton.ItemsSource>
</controls:SplitButton>


来源:https://stackoverflow.com/questions/27337092/how-to-manually-bind-static-items-to-splitbutton-mahapps-via-xaml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!