【问题标题】:Listbox Binding Problem列表框绑定问题
【发布时间】:2011-11-05 13:32:33
【问题描述】:

请解决我的问题,我的列表框没有绑定,我不知道为什么:(

class TLocation
{
    public string name;
}

主窗口:

<Window x:Class="WpfApplication5.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication5"
        Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded">

    <Window.Resources>
        <DataTemplate DataType="{x:Type local:TLocation}" x:Key="myTaskTemplate">
            <TextBlock Height="23" HorizontalAlignment="Left" Margin="1" Name="textBlock1" Text="{Binding Path=name, FallbackValue=name}" VerticalAlignment="Top" />
        </DataTemplate>
    </Window.Resources>

    <Grid>
        <ListBox Height="131" HorizontalAlignment="Left" Margin="29,44,0,0" Name="listBox1" VerticalAlignment="Top" Width="200" ItemTemplate="{StaticResource myTaskTemplate}" />
    </Grid>
</Window>

主窗口代码:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        List<TLocation> list = new List<TLocation>();

        TLocation temp = new TLocation();

        temp.name = "hi";

        list.Add(temp);

        listBox1.ItemsSource = list;
    }
}

【问题讨论】:

    标签: wpf data-binding listbox wpf-controls wpftoolkit


    【解决方案1】:

    namefield,但您只能绑定到公共properties。如果名称在运行时更改,您可能还想实现 INotifyPropertyChanged。如果您不熟悉数据绑定,请务必阅读 the overview

    例如

    public class TLocation : INotifyPropertyChanged
    {
        private string _name = null;
        public string Name
        {
            get { return _name; }
            set
            {
                if (_name != value)
                {
                    _name = value;
                    OnPropertyChanged("Name");
                }
            }
        }
    
        public event PropertyChangedEventHandler PropertyChanged;
    
        protected virtual void OnPropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
    

    (绑定也是区分大小写的,并且您的大小写不遵循conventions,所以我在我的示例中更改了它,这里Binding.Path 需要为Name。) p>

    【讨论】:

    • @ArMaN:你把绑定路径改成Name了吗?另外:There are ways to debug bindings,告诉我你遇到的错误(并在以后的问题中发布它们)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-10
    • 2010-11-22
    • 2012-12-16
    • 2011-11-22
    • 2013-01-31
    相关资源
    最近更新 更多