wpf - 防止在 XAML 中编写大量重复代码

标签 wpf xaml copy-paste

我有 XAML:

<TextBlock Text="Param 1 name" Margin="6,6,0,0"></TextBlock>
<TextBox Text="{Binding Param1Value, UpdateSourceTrigger=PropertyChanged}" Margin="6,6,0,0"></TextBox>

<TextBlock Text="Param 2 name" Margin="6,6,0,0"></TextBlock>
<TextBox Text="{Binding Param2Value, UpdateSourceTrigger=PropertyChanged}" Margin="6,6,0,0"></TextBox>

...

<TextBlock Text="Param N name" Margin="6,6,0,0"></TextBlock>
<TextBox Text="{Binding ParamNValue, UpdateSourceTrigger=PropertyChanged}" Margin="6,6,0,0"></TextBox>

如何优化此代码以防止复制粘贴? 控件、样式、ContentControl 还是 DataTemplate?

我可以使用 Style 来重用边距,但是如何重用这对 TexBlock 和 TextBox 的结构?

最佳答案

创建一个具有两个属性(例如,Caption 和 Text)的 UserControl,并将 TextBlock 绑定(bind)到 Caption 并将 TextBox 绑定(bind)到 Text 属性。

如果您想让设计人员创建自定义模板以便他可以完全控制 UI 设计,您也可以使用模板化控件。

UserControl vs. Custom/Templated Control (阅读整个线程以获得最大利益):

Well the difference between user control and custom control is that If you have a portion of views or UI which will be used repeatedly in your own project, using UserControl is a much simpler and preferred way, but if you have a portion of UI and functionality which you believe will be used aross different projects, then using custom control is the right approach.

关于wpf - 防止在 XAML 中编写大量重复代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9014522/

相关文章:

c# - WPF:创建在构造函数中需要参数的应用程序资源 - 如何?

c# - 多次触发剪贴板更新事件

excel - 通过链接将一张纸上的列转置为另一张纸上的行

c# - 在 C#/XAML 应用程序中无法绑定(bind)到属于 WindowsFormsHost 子对象的属性的解决方法?

c# - 为什么 ListView 在 MVVM 中不更新

c# - 在 WPF 中创建 UI 设置的正确方法是什么?

c# - 我可以在 XAML 中处理抛出的异常吗?

c# - 数据绑定(bind) Entity Framework 导航属性 - 处理更改

c# - 从 DataContext 获取值到 MarkupExtension

python - 我如何创建一个 powershell 脚本来将数千个日志文件从一个位置移动到另一个位置?