开发者

Listbox Binding Problem

开发者 https://www.devze.com 2023-03-31 02:53 出处:网络
Please solve my problem, my listbox don\'t bind, i don\'t why :( class TLocation { public string name; } Main Window:

Please solve my problem, my listbox don't bind, i don't why :(

class TLocation
{
    public string name;
}

Main Window:

<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>

Main Window Code:

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开发者_C百科.Add(temp);

        listBox1.ItemsSource = list;
    }
}


name is a field, you can only bind to public properties though. You might also want to implement INotifyPropertyChanged if the name changes at runtime. If you are new to databinding make sure to read the overview.

e.g.

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));
        }
    }
}

(Binding is also case senstitive and your capitalization is not following the conventions so i changed it in my example, here the Binding.Path would need to be Name.)

0

精彩评论

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