WPF列表框IsChecked属性

时间:2015-03-23 14:50:43

标签: c# wpf listbox

我遇到属性绑定问题。它不起作用。

<Window x:Class="ProblemWithScrolling.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<StackPanel>
    <ListBox ItemsSource="{Binding Test}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <CheckBox Content="{Binding Name}" IsChecked="{Binding Check}"></CheckBox>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
    <Label Height="40" Width="200" Content="Test"></Label>
</StackPanel>

代码隐藏 *

namespace ProblemWithScrolling
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    private List<DataStruct> test;
    public List<DataStruct> Test
    {
        get { return test; }
        set { test = value; }
    }
    public string check;
    public string Check
    {
        get { return check; }
        set { check = value; if (value == "True") { Debug.WriteLine(this.Name); }
        }
    }
    public MainWindow()
    {
        Test = new List<DataStruct>();
        Test.Add(new DataStruct { Name = "First", Number = "2" });
        Test.Add(new DataStruct { Name = "Second", Number = "2" });
        Test.Add(new DataStruct { Name = "Third", Number = "2" });
        InitializeComponent();
        this.DataContext = this;
    }
}

public class DataStruct
{
    public string Name { get; set; }
    public string Number { get; set; }
}

}

是否可以将IsChecked属性绑定到Check属性。我知道它正在尝试将Check属性发现到DataStruct

2 个答案:

答案 0 :(得分:1)

  1. 你的财产需要是一个布尔。
  2. 您的财产需要实施正确的INotifyPropertyChanged处理。

  3. 您的属性需要是数据上下文的属性。

  4. OR

    1. 您的Binding需要访问其他数据上下文。
    2. 您可以使用this handy cheat sheet查找将来可能需要的任何奇怪的绑定。

答案 1 :(得分:0)

你没有this.Name MainWindow。移动Check中的DataStruct属性。将此属性设置为Boolean

是一件好事
public class DataStruct
{
    public Boolean check;

    public Boolean Check
    {
        get { return check; }
        set
        {
            check = value;
            if (value) { Debug.WriteLine(this.Name); }
        }
    }

    public string Name { get; set; }

    public string Number { get; set; }
}

MainWindow中,您可以使用它:

public partial class MainWindow : Window
{
    private List<DataStruct> test;

    public MainWindow()
    {
        Test = new List<DataStruct>();
        Test.Add(new DataStruct { Name = "First", Number = "2", Check = true });
        Test.Add(new DataStruct { Name = "Second", Number = "2" });
        Test.Add(new DataStruct { Name = "Third", Number = "2" });
        InitializeComponent();
        this.DataContext = this;
    }

    public List<DataStruct> Test
    {
        get { return test; }
        set { test = value; }
    }
}