【发布时间】:2020-12-09 17:36:31
【问题描述】:
我的UserControl.xaml 文件中有以下标记:
<Grid DataContext="{Binding ElementName=ControlForProjectSettings, Path=ViewModel}"
ColumnSpan="2" HorizontalAlignment="Center" VerticalAlignment="Center">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2" Style="{StaticResource HeadingTextBlocksStyle}"
Text="Project settings"/>
<TextBlock Grid.Row="1" Grid.Column="0" Style="{StaticResource StandardTextBlocksStyle}"
Text="Project Number"/>
<TextBox Grid.Row="1" Grid.Column="1" Style="{StaticResource DefaultTextBoxesStyle}"
Text="{Binding ProjectNumber,
Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
<TextBlock Grid.Row="2" Grid.Column="0" Style="{StaticResource StandardTextBlocksStyle}"
Text="Customer Name"/>
<TextBox Grid.Row="2" Grid.Column="1" Style="{StaticResource DefaultTextBoxesStyle}"
Text="{Binding CustomerName,
Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</Grid>
我在其他用户控件中使用了类似的方法,我想在其中显示一个 TextBlock 和一个 TextBox 并排显示。
现在我想摆脱重复的代码,并为这样的代码块使用模板:
<TextBlock Grid.Row="1" Grid.Column="0" Style="{StaticResource StandardTextBlocksStyle}"
Text="Project Number"/>
<TextBox Grid.Row="1" Grid.Column="1" Style="{StaticResource DefaultTextBoxesStyle}"
Text="{Binding ProjectNumber,
Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
因此我的想法是创建一个如下所示的ControlTemplate:
<ControlTemplate x:Key="OneSettingsEntry">
<StackPanel Orientation="Horizontal">
<TextBlock Style="{StaticResource StandardTextBlocksStyle}" Text="{TemplateBinding Text}" />
<TextBox Style="{StaticResource DefaultTextBoxesStyle}"
Text="{TemplateBinding TextBoxContent}" />
</StackPanel>
</ControlTemplate>
我想在UserControl.xaml 和其他User Controls 中使用该模板:
<Grid DataContext="{Binding ElementName=ControlForProjectSettings, Path=ViewModel}">
<StackPanel>
<ListView>
<ListViewItem Template="{StaticResource OneSettingsEntry }"/>
</ListView>
</StackPanel>
</Grid>
但是如何为ListViewitem 设置Text 或TextBoxContent 属性?
我已经找到与此问题相关的其他文章,但没有设法解决它。
如果您有其他建议而不是使用 ControlTemplate,这也可以解决我的问题,然后提出来。
【问题讨论】:
标签: c# wpf xaml datatemplate controltemplate