【发布时间】:2017-02-21 12:34:02
【问题描述】:
我查看了那些关于做 DataTemplate 的文章:
以及关于 DataTemplate 的内容取决于属性类型:
- WPF DataTemplate Binding depending on the type of a property
- Dynamically display a control depending on bound property using WPF
我正在尝试根据属性值显示具有不同控件的属性。我有这个部分工作的 Xaml。我有两个问题:
该属性正在使用正确的控件显示,但是当我设置该值时,它不会返回到该属性。表示未调用 My 属性的“集合”(但在创建 DataTemplate 之前)。我检测到设置属性的问题是关于 ="{Binding Path=.}" 但我找不到其他设置的解决方案。
此外,为了使其工作,我必须将值“隔离”到单个 ViewModel 中,以便 DataTemplate 不会影响所有其他控件。
你能帮我找到更好的解决方案来解决这两个问题吗?
这是我的视图的 xaml 代码,它与具有“ChangingDataType”的 MyContainerViewModel 链接:
<UserControl >
<UserControl.Resources>
<!-- DataTemplate for strings -->
<DataTemplate DataType="{x:Type sys:String}">
<TextBox Text="{Binding Path=.}" HorizontalAlignment="Stretch"/>
</DataTemplate>
<!-- DataTemplate for bool -->
<DataTemplate DataType="{x:Type sys:Boolean}">
<CheckBox IsChecked="{Binding Path=.}" />
</DataTemplate>
<!-- DataTemplate for Int32 -->
<DataTemplate DataType="{x:Type sys:Int32}">
<dxe:TextEdit Text="{Binding Path=.}" MinWidth="50" Mask="d" MaskType="Numeric" HorizontalAlignment="Stretch"/>
<!--<Slider Maximum="100" Minimum="0" Value="{Binding Path=.}" Width="100" />-->
</DataTemplate>
<!-- DataTemplate for decimals -->
<DataTemplate DataType="{x:Type sys:Decimal}">
<!-- <TextBox Text="{Binding Path=.}" MinWidth="50" HorizontalAlignment="Stretch" />-->
<dxe:TextEdit Text="{Binding Path=.}" MinWidth="50" Mask="f" MaskType="Numeric" HorizontalAlignment="Stretch" />
</DataTemplate>
<!-- DataTemplate for DateTimes -->
<DataTemplate DataType="{x:Type sys:DateTime}">
<DataTemplate.Resources>
<DataTemplate DataType="{x:Type sys:String}">
<TextBlock Text="{Binding Path=.}"/>
</DataTemplate>
</DataTemplate.Resources>
<DatePicker SelectedDate="{Binding Path=.}" HorizontalAlignment="Stretch"/>
</DataTemplate>
</UserControl.Resources>
<ContentPresenter Content="{Binding MyChangingPropery}"/>
</UserControl>
关于 2 的更多信息:
我想在视图中有一个标签和一个随对象而变化的属性。像这样:
<UserControl>
<UserControl.Resources>
<!-- ...DataTemplate here... -->
</UserControl.Resources>
<StackPanel>
<Label Content="Allo"/>
<ContentPresenter Content="{Binding MyChangingPropery}"/>
</StackPanel>
</UserControl>
但是如果我把DataTemplate放在这个UserControl资源上,也会影响到Label“allo”。所以我必须创建另一个包含 DataTemplate 和 MyChangingProperty 的视图,以便标签 Allo 不会受到影响。但是为一个属性创建的额外视图对我来说有点难看,我相信有更好的方法来隔离 DataTemplate,这样它就可以只应用于一个 UIControl。
<UserControl >
<StackPanel>
<Label Content="Allo"/>
<ContentPresenter Content="{Binding MyContainerViewModel}"/>
</StackPanel>
</UserControl>
注意:这里的 MyContainerViewModel 与描述的第一个视图相关联。
提前致谢!
【问题讨论】:
-
你能解释一下第2个问题是什么吗? WPF 中资源的范围是设计使然。
-
当然,我会为数字 2 添加更多信息。
标签: wpf xaml mvvm binding datatemplate