开发者

WPF Getting CheckBox Content

I am using Data Templates to set the values of checkboxes within a combobox as such:

<ComboBox Margin="118,117,163,1开发者_StackOverflow64" ItemsSource="{Binding collection}">
        <ComboBox.ItemTemplate>
            <DataTemplate>
                <CheckBox Content="{Binding Name}"/>
            </DataTemplate>
        </ComboBox.ItemTemplate>
    </ComboBox>

This works as it should. My problem is, when the user checks the box, I need to be able to get the content value stored within the checkbox. Is this possible?

Thanks.


You need to bind the Checkbox's IsChecked property to another property on the backing object for each item. i.e. the type which has the Name should expose a boolean property IsSelected.

Databinding will update the IsSelected property appropriately, which would be easy for you to access in code. e.g. you can loop over the list and filter all the items that have IsSelected = false.

Code Sample

XAML

<StackPanel>
        <ComboBox ItemsSource="{Binding Items}">
            <ComboBox.ItemTemplate>
                <DataTemplate>
                    <CheckBox Content="{Binding Name}" IsChecked="{Binding IsSelected}"/>
                </DataTemplate>
            </ComboBox.ItemTemplate>
        </ComboBox>
        <Button Click="EvaluateSelectedItems">Show Selected</Button>
        <TextBlock>Selected Items</TextBlock>
        <ListBox ItemsSource="{Binding SelectedItems}" DisplayMemberPath="Name" Background="AliceBlue"/>
    </StackPanel>

Code-behind

public MainWindow()
{
    InitializeComponent();
    this.DataContext = this;

    Items = new List<ItemVM>
                {
                    new ItemVM {IsSelected = false, Name = "Firefox"},
                    new ItemVM {IsSelected = false, Name = "Chrome"},
                    new ItemVM {IsSelected = false, Name = "IE"}
                };
}

public IEnumerable<ItemVM> Items { get; set; }
private IEnumerable<ItemVM> _selectedItems;
public IEnumerable<ItemVM> SelectedItems
{
    get { return _selectedItems; }
    set
    {
        _selectedItems = value;
        if (PropertyChanged != null)
            this.PropertyChanged(this, new PropertyChangedEventArgs("SelectedItems"));
    }
}

private void EvaluateSelectedItems(object sender, RoutedEventArgs e)
{
    SelectedItems = Items.Where(item => item.IsSelected);
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜