考虑以下 2 个 XAML 片段(在文件中并排显示):
<Button
x:Name="BuyButton"
Margin="0,0,1,1"
IsEnabled="{Binding CanBuy}"
>
<StackPanel
DataContext="{Binding Product}">
<TextBlock
Foreground="Red"
Text="BUY" />
<TextBlock
Foreground="Red"
Text="{Binding BuyPrice}" />
</StackPanel>
</Button>
<Button
x:Name="SellButton"
Margin="0,0,1,1"
IsEnabled="{Binding CanSell}"
>
<StackPanel
DataContext="{Binding Product}">
<TextBlock
Foreground="Red"
Text="SELL" />
<TextBlock
Foreground="Red"
Text="{Binding SellPrice}" />
</StackPanel>
</Button>
如何删除 WPF 中的重复项?这种类型的按钮我有大约 4 次使用(此处显示 2 次),它们的 80% 相同,如果不是更多的话。我可以将其提取到用户控件中并在其上放置一些 DP,然后我将拥有一个控件,但我担心我会开始在我的代码库中乱扔大量用户控件(我有很多“一次性"这样的情况)。我不喜欢这里的 DataTemplate 解决方案,因为我仍然需要两个模板,这将有重复的代码。在不创建一堆模板/控件的情况下,有没有办法让这段代码遵循 DRY?