WPF绑定问题

时间:2010-06-01 19:03:58

标签: c# wpf binding

我在UI中有一些绑定:

   <Window x:Class="Tester.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="377" Width="562" xmlns:my="clr-namespace:MyApp">
        <Grid>
        <TextBlock Text="{Binding Path=current.Text}"  Name="Text1" />
        <TextBlock Text="{Binding Path=current.o.Text}"  Name="Text2"  />

</Grid>
</Window>

代码:

class Coordinator : INotifyPropertyChanged{
     List<Myclass1> list;
     int currId = 0;
     public Myclass1 current{
              return list[currId];
           }
     public int CurrId
    {
        get { return currId; }
        set
        {
                currId = value;
                this.PropertyChanged(this,new PropertyChangedEventArgs("current"));


         }
}
class Myclass1{
     public string Text{get;}
     public Myclass2 o{get;}
}

class Myclass2{
     public string Text{get;}
}

当currId改变UI中的Tex1也会改变,但Text2不会改变。

我假设发生这种情况是因为Text2的源未更新。 有谁知道如何解决它?

3 个答案:

答案 0 :(得分:0)

我不确定这是否是你要找的东西,但对于类似的东西,我使用PropertyObserver class中的Josh Smith's MVVM framework

答案 1 :(得分:0)

假设您正确地实现了类,它应该工作。通过一些修复,我的代码如下所示:

<Window x:Class="WpfBindingTest.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid>
    <StackPanel>
        <TextBlock Text="Enter 0, 1 or 2 below and press Tab:"/>
        <TextBox Text="{Binding CurrId}"/>
        <Button/> <!--Button here is just for another tab stop-->
        <TextBlock Text="{Binding Path=current.Text}"  Name="Text1" />
        <TextBlock Text="{Binding Path=current.o.Text}"  Name="Text2"  />
    </StackPanel>
</Grid>
</Window>

它适用于这样实现的类:

public partial class Window1: Window {
    public Window1() {
        InitializeComponent();
        DataContext = new Coordinator();
    }
}

class Coordinator: INotifyPropertyChanged {
    List<Myclass1> list;
    int currId = 0;

    public Myclass1 current {
        get { return list[currId]; }
    }

    public int CurrId {
        get { return currId; }
        set {
            currId = value;
            this.PropertyChanged(this, new PropertyChangedEventArgs("current"));
        }
    }

    public Coordinator() {
        list = new List<Myclass1>(){
            new Myclass1(){ Text = "1", o = new Myclass2(){Text="1.1"}},
            new Myclass1(){ Text = "2", o = new Myclass2(){Text="2.2"}},
            new Myclass1(){ Text = "3", o = new Myclass2(){Text="3.3"}}
        };
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

class Myclass1 {
    public string Text { get; set; }
    public Myclass2 o { get; set; }
}

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

答案 2 :(得分:0)

也许你需要在Myclass2中实现INotifyPropertyChanged。