DisplayNameAttribute(显示属性)
DisplayName
为具有零(0)参数的属性,事件或公共 void 方法设置显示名称。
public class Employee
{
[DisplayName(@"Employee first name")]
public string FirstName { get; set; }
}
XAML 应用程序中的简单用法示例
<Window x:Class="WpfApplication.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:wpfApplication="clr-namespace:WpfApplication"
Height="100" Width="360" Title="Display name example">
<Window.Resources>
<wpfApplication:DisplayNameConverter x:Key="DisplayNameConverter"/>
</Window.Resources>
<StackPanel Margin="5">
<!-- Label (DisplayName attribute) -->
<Label Content="{Binding Employee, Converter={StaticResource DisplayNameConverter}, ConverterParameter=FirstName}" />
<!-- TextBox (FirstName property value) -->
<TextBox Text="{Binding Employee.FirstName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
</StackPanel>
</Window>
namespace WpfApplication
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private Employee _employee = new Employee();
public MainWindow()
{
InitializeComponent();
DataContext = this;
}
public Employee Employee
{
get { return _employee; }
set { _employee = value; }
}
}
}
namespace WpfApplication
{
public class DisplayNameConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
// Get display name for given instance type and property name
var attribute = value.GetType()
.GetProperty(parameter.ToString())
.GetCustomAttributes(false)
.OfType<DisplayNameAttribute>()
.FirstOrDefault();
return attribute != null ? attribute.DisplayName : string.Empty;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}