0

我在我的应用程序中使用 Listbox。

<ListBox Name="lbMain">
   <ListBox.ItemTemplate>
     <DataTemplate>
        <Expander Header="{Binding Converter={StaticResource convCaption}, 
          Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" IsExpanded="True">
        <StackPanel>
          <TextBlock Text={Binding FirstName, Mode=TwoWay,
                                             UpdateSourceTrigger=PropertyChanged}>
          </TextBlock> 
           <TextBlock Text={Binding SecondName, Mode=TwoWay,   pdateSourceTrigger=PropertyChanged}>
          </TextBlock> 
        </StackPanel>
     </DataTemplate>
   </ListBox.ItemTemplate>
</ListBox>

后面的代码

public MainWindow()
{
   MyModel myModel = new MyModel();
   lbMain.ItemSource = myModel;
}

这是模型

public class MyModel
{
   public string FirstName{get; set; }
   public string SecondName{get; set; }
}

这是转换器(convCaption)

  public object Convert(object value, Type targetType, object parameter ...)
  {
     MyModel model =(MyModel)value;
     return string.Format("This is {0}, {1}", Model.FirstName, ModelSecondName)
  }

这一切都有效。但是当我更改 FirstName 或 SecondName 时,我需要更改 Expander 中的 Header。如果我写 {Mode = TwoWay} 显示错误 - “需要路径”。我喜欢为 Expander 编写正确的绑定(以更新的标题)?

4

2 回答 2

2

您需要在您的类上实现INotifyPropertyChanged接口。MyModel请参阅 MSDN 上的INotifyPropertyChanged 接口页面以获取帮助。此外,您实际上并不需要 aConverter来加入这两个名称......有一个更简单的方法......只需覆盖ToString()该类中的方法:

public override string ToString()
{
    return string.Format("This is {0}, {1}", FirstName, SecondName);
}
于 2013-09-10T08:32:15.940 回答
1

首先,您MyModel需要每次实施INotifyPropertyChanged和引发事件或发生变化,如下所示:PropertyChangedFirstNameSecondName

public class MyModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged(string propertyName)
    {
        var handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }

    private string _firstName;

    public string FirstName
    {
        get { return _firstName; }
        set
        {
            if (_firstName == value) return;
            _firstName = value;
            OnPropertyChanged("FirstName");
        }
    }

    private string _secondName;

    public string SecondName
    {
        get { return _secondName; }
        set
        {
            if (_secondName == value) return;
            _secondName = value;
            OnPropertyChanged("SecondName");
        }
    }
}

然后你可以像这样MultiBinding使用StringFormat

<Expander>
    <Expander.Header>
        <TextBlock>
            <TextBlock.Text>
                <MultiBinding StringFormat="{}This is {0} {1}">
                    <Binding Path="FirstName"/>
                    <Binding Path="SecondName"/>
                </MultiBinding>
            </TextBlock.Text>
        </TextBlock>
    </Expander.Header>
</Expander>
于 2013-09-10T08:52:57.287 回答