我有一个StatusBarItem
,我想在任何给定时刻显示以下消息"X/Y",其中 X 是当前所选元素的行号,Y 是行计数。
现在,如果我在 xaml 中使用 Content="{Binding ElementName=lvTabela, Path=SelectedIndex}"
代码,我能够获取要显示的第一个属性,但我不确定如何同时获得这两个属性。
我想我总是可以使用两个相邻的StatusBarItem
元素,但我也想学习如何做到这一点。
哦,当我们在做的时候,我将如何增加所选索引?基本上,我希望它显示 0 到 rowCount,而不是 -1 到 rowCount-1。我见过有人使用格式化程序将其他文本添加到他们的数据绑定中,但我不确定如何像这样操作数据。
您有 2 个选项:
要么将StatusbarItem
的Content
设置为TextBlock
,以便将StringFormat
与MultiBinding
一起使用,如下所示:
<StatusBarItem>
<StatusBarItem.Content>
<TextBlock>
<TextBlock.Text>
<MultiBinding StringFormat="{}{0}/{1}">
<MultiBinding.Bindings>
<Binding ElementName="listView"
Path="SelectedIndex" />
<Binding ElementName="listView"
Path="Items.Count" />
</MultiBinding.Bindings>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</StatusBarItem.Content>
</StatusBarItem>
或使用MultiBinding
上的转换器,不必使用TextBlock
<Window.Resources>
<local:InfoConverter x:Key="InfoConverter" />
</Window.Resources>
...
<StatusBarItem>
<StatusBarItem.Content>
<MultiBinding Converter="{StaticResource InfoConverter}">
<MultiBinding.Bindings>
<Binding ElementName="listView"
Path="SelectedIndex" />
<Binding ElementName="listView"
Path="Items.Count" />
</MultiBinding.Bindings>
</MultiBinding>
</StatusBarItem.Content>
</StatusBarItem>
和信息转换器.cs:
class InfoConverter : IMultiValueConverter {
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) {
return values[0].ToString() + "/" + values[1].ToString();
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) {
throw new NotImplementedException();
}
}
当StringFormat
返回一个字符串时,StatusBarItem
期望一个对象,因此为什么我们不能在没有TextBlock
的情况下将StringFormat
与MultiBinding
一起使用,可以在其Text
字段中获取字符串。
至于您关于如何增加SelectedIndex
值的第二个问题,您可以使用转换器轻松做到这一点,
只需将Convert(...)
功能切换InfoConverter.cs
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) {
return (System.Convert.ToInt32(values[0]) + 1).ToString() + "/" + values[1].ToString();
}