如何将数据绑定到控件模板中加载的用户控件?
How to Binding data to User Control loaded in Control Template?
我的 CMainViewModel 有一个 属性 叫做 AnalogGaugeValue1
在我的 Window 上,我有一个数据模板,如下所示。我使用此模板加载名为 AnalogIOView 的用户控件,并尝试将 AnalogIOView 内的依赖项 属性、GaugeValue1DP 绑定到 AnalogGaugeValue1
<Window>
<Window.Resources>
<DataTemplate x:Key="AnalogIOViewTemplate" DataType="{x:Type local:CMainViewModel}">
<local:AnalogIOView
GaugeValue1DP="{Binding Path=AnalogGaugeValue1}" />
</DataTemplate>
</Window.Resources>
<Window>
我使用 ContentControl 在我的 Window 中加载 AnalogIOViewTemplate,如下所示
<Grid>
<ContentControl>
<ContentControl.Style>
<Style TargetType="{x:Type ContentControl}">
<Setter Property="ContentTemplate" Value="
{StaticResource AnalogIOViewTemplate }" />
</Style>
</ContentControl.Style>
</ContentControl>
</Grid>
用户控件在我的 Window 上正确显示,但我无法通过在 CMainViewModel 中绑定来设置 Analog Gauge 值。
但是,如果我只是直接加载用户控件(不使用控件模板),那么它会正常工作,如下所示
<Grid>
<local:AnalogIOView GaugeValue1DP="{Binding Path=AnalogGaugeValue1}" />
</Grid>
我的问题是为什么在使用内容控件模板和数据模板加载用户控件时它不起作用
感谢您的帮助
您必须设置 Content
属性,并且不在 DataTemplate 上设置 x:Key
也会更简单。然后它将自动被选为 ContentControl 的 ContentTemplate。
<Window>
<Window.Resources>
<DataTemplate DataType="{x:Type local:CMainViewModel}">
<local:AnalogIOView GaugeValue1DP="{Binding AnalogGaugeValue1}"/>
</DataTemplate>
</Window.Resources>
<Grid>
<ContentControl Content="{Binding}"/>
</Grid>
<Window>
我的 CMainViewModel 有一个 属性 叫做 AnalogGaugeValue1
在我的 Window 上,我有一个数据模板,如下所示。我使用此模板加载名为 AnalogIOView 的用户控件,并尝试将 AnalogIOView 内的依赖项 属性、GaugeValue1DP 绑定到 AnalogGaugeValue1
<Window>
<Window.Resources>
<DataTemplate x:Key="AnalogIOViewTemplate" DataType="{x:Type local:CMainViewModel}">
<local:AnalogIOView
GaugeValue1DP="{Binding Path=AnalogGaugeValue1}" />
</DataTemplate>
</Window.Resources>
<Window>
我使用 ContentControl 在我的 Window 中加载 AnalogIOViewTemplate,如下所示
<Grid>
<ContentControl>
<ContentControl.Style>
<Style TargetType="{x:Type ContentControl}">
<Setter Property="ContentTemplate" Value="
{StaticResource AnalogIOViewTemplate }" />
</Style>
</ContentControl.Style>
</ContentControl>
</Grid>
用户控件在我的 Window 上正确显示,但我无法通过在 CMainViewModel 中绑定来设置 Analog Gauge 值。
但是,如果我只是直接加载用户控件(不使用控件模板),那么它会正常工作,如下所示
<Grid>
<local:AnalogIOView GaugeValue1DP="{Binding Path=AnalogGaugeValue1}" />
</Grid>
我的问题是为什么在使用内容控件模板和数据模板加载用户控件时它不起作用
感谢您的帮助
您必须设置 Content
属性,并且不在 DataTemplate 上设置 x:Key
也会更简单。然后它将自动被选为 ContentControl 的 ContentTemplate。
<Window>
<Window.Resources>
<DataTemplate DataType="{x:Type local:CMainViewModel}">
<local:AnalogIOView GaugeValue1DP="{Binding AnalogGaugeValue1}"/>
</DataTemplate>
</Window.Resources>
<Grid>
<ContentControl Content="{Binding}"/>
</Grid>
<Window>