【发布时间】:2014-07-11 16:53:15
【问题描述】:
对于不变的状态列表,我有一个友好名称的静态列表。这些友好的名称(绿色、黄色、红色)与底层状态值(0、1、2..)相关联。对于给定的项目,此视图将允许用户从列表中选择一个状态,并显示他们从列表中选择的状态的描述,因为它与他们当前正在编辑的项目有关。
ViewModel 公开了用户正在编辑的对象,该对象在字典中具有状态集合。例如,从 ListBox 中选择一个状态,如绿色,将使用所选项目的标记(在本例中为 0)显示字典中的文本,以显示该键的值(在本例中为“一切正常”)。
我无法手动设置 ListBoxItem 的值属性,因此我必须使用标签。该模型当前适用于在 Selected Item 更改时显示集合中每个状态的文本。 TextBox 使用 MultiBinding 到 Dictionary Collection 和 ListBox 来显示正确的文本。
这是我所拥有的:
<ListBox Name="StatusItems" Style="{StaticResource MyList}">
<ListBoxItem Content="Green" Tag="0"></ListBoxItem>
<ListBoxItem Content="Yellow" Tag="1" />
<ListBoxItem Content="Yellow Audible" Tag="2" />
<ListBoxItem Content="Yellow Flashing" Tag="3" />
<ListBoxItem Content="Yellow Flashing Audible" Tag="4" />
<ListBoxItem Content="Orange" Tag="5" />
<ListBoxItem Content="Orange Audible" Tag="6" />
<ListBoxItem Content="Orange Flashing" Tag="7" />
<ListBoxItem Content="Orange Flashing Audible" Tag="8" />
<ListBoxItem Content="Red" Tag="9" />
<ListBoxItem Content="RedAudible" Tag="10" />
<ListBoxItem Content="RedFlashing" Tag="11" />
<ListBoxItem Content="RedFlashingAudible" Tag="12" />
<ListBoxItem Content="Gray" Tag="13" />
</ListBox>
<TextBox MinLines="5" TextWrapping="Wrap" AcceptsReturn="True" AcceptsTab="True">
<TextBox.Text>
<MultiBinding>
<MultiBinding.Converter>
<conv:DictionaryItemConverter />
</MultiBinding.Converter>
<Binding Path="Alarm.StatusDescriptions" Mode="TwoWay" />
<Binding Path="SelectedItem.Tag" ElementName="StatusItems" />
</MultiBinding>
</TextBox.Text>
</TextBox>
<Button Content="Save" Command="{Binding Path=SaveCommand}" IsEnabled="{Binding Path=Saveable}" />
模型崩溃的地方是我尝试保存时。我不确定如何将对状态所做的更改保留回字典中的正确项目,部分原因是多值转换器。我想也许我可以在 ViewModel 上添加一个 SelectedStatus int,然后将所选列表框项的标记属性单向绑定到此属性,以便在单击保存时我会知道使用哪个键来更新描述。
我正在尝试这样的事情(当然语法是错误的)
<ListBox SelectedValue="{Binding Path=SelectedStatus, Mode=OneWayToSource, RelativeSource={RelativeSource Self.SelectedItem.Tag}}" >
我能否以某种方式将 SelectedItem 的标记属性绑定到我的视图上的属性?还是我应该放弃整个想法并走另一条路?
【问题讨论】:
-
有更简单的方法来填充列表框。容易得多。在 MVVM 中,没有理由不使用它们。
-
@HenkHolterman 我们是说我也应该创建一些集合来绑定列表框吗?我可以这样做,只是该列表是一个静态不变的状态列表。绿色只是用户的友好名称,他们正在编辑的底层状态描述是状态 0。即使我将它绑定到不同的集合,它也不会是字典,并且它们之间不会存在一对一的关联列出所选项目和 viewmodels 字典条目。
-
我不介意投反对票,但如果我知道出了什么问题,我会很感激,这样我以后可能会避免它。
-
至少你应该避免使用标签。创建一个
class { ColorName, Value }并在 ViewModel 或 XAML 中实例化一个列表。