Nic*_*tch 4 c# silverlight xaml silverlight-3.0
我正在尝试将IsLoading属性绑定到UI的LayoutRoot Grid的Cursor属性.我试图让主应用程序光标变成沙漏,只要属性说它正在加载.
我绑定财产如下:
<Grid Cursor="{Binding IsLoading, Converter={StaticResource CursorConverter}}">
Run Code Online (Sandbox Code Playgroud)
键"CursorConverter"映射到资源中的BoolToCursorConverter.转换器代码是:
public class BoolToCursorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (parameter == null)
return ((bool)value == true) ? Cursors.Wait : Cursors.Arrow;
return false;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
Cursor cursor = value as Cursor;
if (cursor != null)
return cursor == Cursors.Wait ? true : false;
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
当我尝试运行它时虽然我得到了XamlParseException"给定的密钥在字典中不存在."
任何帮助将不胜感激,谢谢,
为什么你会得到那个错误
您在Resources属性的内容中是否有类似的内容?
<local:BoolToCursorConverter x:Key="CursorConverter" />
Run Code Online (Sandbox Code Playgroud)
如果没有,那就错了,但我猜你已经做到了.
在这种情况下,我怀疑你已将它放在它适用的Resources属性中Grid.这就是为什么它找不到的原因. StaticResource在解析Xaml时立即解析.因此,在使用之前,所使用的任何密钥必须已经加载到资源字典中.Xaml解析器对Grid的Resources属性内容一无所知,因为它尚未处理它.因此: -
<UserControl>
<Grid Cursor="{Binding IsLoading, Converter={StaticResource CursorConverter}}">
<Grid.Resources>
<local:BoolToCursorConverter x:Key="CursorConverter" />
</Grid.Resources>
<!-- Contents here -->
</Grid>
</UserControl>
Run Code Online (Sandbox Code Playgroud)
将失败.在哪里: -
<UserControl>
<UserControl.Resources>
<local:BoolToCursorConverter x:Key="CursorConverter" />
</UserControl.Resources >
<Grid Cursor="{Binding IsLoading, Converter={StaticResource CursorConverter}}">
<!-- Contents here -->
</Grid>
</UserControl>
Run Code Online (Sandbox Code Playgroud)
至少不会失败找到转换器.
你真正需要做什么
我已经提出了上述问题来回答你的问题,但我发现它并没有真正帮助你.您不能像这样绑定到Cursor属性.(它不公开公共标识符字段,Xaml使用NameOfThing +"Property"约定来查找DependencyProperty要绑定的属性的字段).
解决方案是创建一个附属属性: -
public class BoolCursorBinder
{
public static bool GetBindTarget(DependencyObject obj) { return (bool)obj.GetValue(BindTargetProperty); }
public static void SetBindTarget(DependencyObject obj, bool value) { obj.SetValue(BindTargetProperty, value); }
public static readonly DependencyProperty BindTargetProperty =
DependencyProperty.RegisterAttached("BindTarget", typeof(bool), typeof(BoolCursorBinder), new PropertyMetadata(false, OnBindTargetChanged));
private static void OnBindTargetChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
FrameworkElement element = sender as FrameworkElement;
if (element != null)
{
element.Cursor = (bool)e.NewValue ? Cursors.Wait : Cursors.Arrow;
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在你可以像这样进行绑定: -
<Grid local:BoolCursorBinder.BindTarget="{Binding IsLoading}">
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2524 次 |
| 最近记录: |