我有 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/