2

我已经找到了三种不同的方式来表示强制字段标签。但是我不确定谁的使用是理想的。一项要求是标签应支持访问密钥。请帮助我了解应该使用哪些。替代建议也值得赞赏。

<Label Width="200" HorizontalAlignment="Left" Target="{Binding ElementName=mytb}">
    <TextBlock>
        <Run Text="*" Foreground="Red" FontWeight="Heavy" />
        <AccessText Text="_Name"/>
    </TextBlock>
</Label>

<Label VerticalAlignment="Center" HorizontalAlignment="Center" Target="{Binding ElementName=mytb}">
    <StackPanel Orientation="Horizontal" Grid.Row="17" Grid.Column="0" HorizontalAlignment="Right">
        <TextBlock Text="*" Foreground="Red" VerticalAlignment="Center" FontWeight="Heavy"></TextBlock>
        <AccessText Text="_Name:" />
    </StackPanel>
</Label>

<StackPanel Orientation="Horizontal">
    <TextBlock Text="*" Foreground="Red" VerticalAlignment="Center" FontWeight="Heavy"/>
    <Label Content="_Name" VerticalAlignment="Center" Target="{Binding ElementName=mytb}"/>
</StackPanel>
4

2 回答 2

1

如果我必须选择你的一个例子,我会选择第一个,但如果不是,那么我会使用 anAttached Property来代替:

<TextBox Text="{Binding SomeProperty}" Attached:TextBoxProperties.IsMandatory="True" />

当然,您会遇到创建 . 的小问题Attached Property,但红色星号 (*) 是最后一个时代。我的IsMandatory属性基本上会TextBox在它为空时显示一条消息,但这是 WPF ......您可以添加一个红色星号或您可以想象的任何其他内容。您甚至可以使用它在我的示例Attached Property中添加星号Label而不是类似的。TextBox

我的Attached Property作品与我的作品结合在一起LabelLabelColour Attached Properties每个作品都添加了额外的功能......该属性提供了一个从页面读取Label的简单(这是带有 extraControlTemplate的默认模板)。该属性只是让我为 extra 选择不同的颜色,但在使用该属性时在内部设置为。TextBoxTextBlockApp.xamlLabelColourForegroundTextBlockRedIsMandatory

我的观点是:您可以像之前的许多人一样使用旧的红色星号,或者您可以扩展并利用 WPF 提供的功能来提出更好的解决方案。

于 2013-09-04T10:04:44.430 回答
0

“应该使用”是相对的。例如,我们可以从性能方面考虑。这可能意味着使用可以提供较小视觉树的版本。通常,Textblock 对此很轻,但缺少 Target 属性,因此访问键不起作用。从您的解决方案来看,第三个比第二个更好,因为它直接包含 StackPanel 而没有包裹标签。带有 Run 文本元素的第一个解决方案似乎是一个优雅的解决方案,我更喜欢它。关于您想要实现的功能,我会将 TextBox 本身标记为强制性的,例如在绑定上使用验证规则。这样,标记可以在用户键入时出现和消失。参见示例:http ://www.nbdtech.com/Blog/archive/2010/07/05/wpf-adorners-part-3-ndash-adorners-and-validation.aspx. 此外,关于可视化树和决定使用哪些控件,我推荐使用 Snoop 工具:http ://snoopwpf.codeplex.com 。

于 2013-09-04T10:26:14.500 回答