我有这个XAML代码:
public class DatePickerFragment extends DialogFragment implements
DatePickerDialog.OnDateSetListener {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the today date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
DatePickerDialog dp = new DatePickerDialog(getActivity(), this, year, month, day);
// Use the today date as the Min date in the picker
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
dp.getDatePicker().setMinDate(c.getTimeInMillis());
} else {
Log.w(TAG, "API Level < 11 so not restricting date range...");
}
return dp;
}
public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
}
}
现在,当我运行代码时,它会在运行时显示一个预先填写的密码框。
我的理解是,<Window x:Class="MyNamespace.MyClass"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:ignore="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
Title="Log in" WindowStartupLocation="CenterScreen"
Height="192" Width="512" mc:Ignorable="ignore d">
...
<PasswordBox VerticalAlignment="Center" ignore:Password="Correct horse battery stapler" />
...
</Window>
会确保以mc:Ignorable="ignore d"
和d:
开头的属性会被忽略,而且确实适用于ignore:
。
那么为什么它不能用于d:DataContext
,我怎样才能在设计时显示模拟密码,但在运行时显示空密码框?
答案 0 :(得分:1)
...如果无法将该属性解析为基础类型或编程构造,则忽略该元素。
暗示似乎Ignorable
仅用于防止XAML解析器引发任何错误。忽略能力不要忽略。在这种情况下,在该命名空间中有一个非常真实的属性Password
,它不会引发任何问题。
您的DataContext
示例在 blend 命名空间中设置了DataContext
属性,而不是WPF命名空间中的实际DataContext
。工具在设计时使用它,但在运行时会被忽略(如果你忽略了d
,如果你使用d:DataContext
,它实际上会产生错误。)
在设计时设置密码有点棘手,因为它不能绑定到Password
,因为它不是依赖属性(有充分的理由!)。我能想到的唯一解决方案是使用仅在设计时设置值的附加属性:
public static class PasswordHelper
{
public static readonly DependencyProperty DesignPasswordProperty =
DependencyProperty.RegisterAttached("DesignPassword",
typeof(string), typeof(PasswordHelper),
new FrameworkPropertyMetadata(string.Empty, OnDesignPasswordPropertyChanged));
public static void SetDesignPassword(DependencyObject dp, string value)
{
dp.SetValue(DesignPasswordProperty, value);
}
public static string GetDesignPassword(DependencyObject dp)
{
return (string)dp.GetValue(DesignPasswordProperty);
}
private static void OnDesignPasswordPropertyChanged(DependencyObject sender,
DependencyPropertyChangedEventArgs e)
{
if (DesignerProperties.GetIsInDesignMode(sender))
{
var passwordBox = (PasswordBox)sender;
passwordBox.Password = (string)e.NewValue;
}
}
}
并像这样使用它:
<PasswordBox ap:PasswordHelper.DesignPassword="Correct horse battery stapler" />