Em1*_*Em1 6 c# data-binding wpf dynamicresource
首先是我开始的代码:
<ribbon:RibbonMenuButton IsEnabled="{Binding ForegroundIsConfigurable}"
SmallImageSource="{Binding Source={StaticResource imageSource},
Path=Source,
UpdateSourceTrigger=OnPropertyChanged}">
Run Code Online (Sandbox Code Playgroud)
虽然这个绑定正在编译并运行良好,但我不满意的原因是imageSource
运行时更改.
StaticResource标记扩展:通过查找对已定义资源的引用,为任何XAML属性属性提供值.该资源的查找行为类似于加载时查找,它将查找先前从当前XAML页面的标记以及其他应用程序源加载的资源,并将生成该资源值作为运行中的属性值时间对象.
由于imageSource
在运行时期间值的变化,我不得不StaticResource
改为DynamicResource
.但该属性Source
不是依赖属性,因此以下代码将引发运行时错误:
SmallImageSource="{Binding Source={DynamicResource imageSource},
Path=Source,
UpdateSourceTrigger=LostFocus}
Run Code Online (Sandbox Code Playgroud)
出于这个原因,我需要直接绑定动态资源SmallImageSource
,这是一个依赖属性:
SmallImageSource="{DynamicResource imageSource}"
Run Code Online (Sandbox Code Playgroud)
这又会引发运行时错误,因为imageSource
它的类型是Image
.SmallImageSource
期望值为type的类型ImageSource
.
现在可以建议将数据上下文设置为我的动态资源并适当地绑定属性.如果我这样做,我会杀死IsEnabled
另一个属性的绑定DataContext
.
据我所知,MultiBinding
也不是解决方案,因为这提供了一种机制来将属性绑定到多个源,但不提供针对不同上下文和源的绑定不同属性.
在考虑如何继续下去时,我想到幸运的是,我可以将ImageSource
钻井平台变成一个IValueConverter
.在我给定的数据上下文中,我RibbonMenuButton
有一个具有适当值的字符串值,这实际上也是我的来源ImageSource
.
无论如何,我仍然想知道如果我没有其他方法,即如果两个源都在不同的数据上下文中,我将如何解决问题.有什么我没看到的吗?如何通过覆盖DataContext
和绑定动态资源的属性来确保不杀死其他绑定?
这imageSource
与DrawingImage msdn页面上的XAML示例非常相似.
<Image x:Key="imageSource">
<Image.Source>
<DrawingImage>
...
Run Code Online (Sandbox Code Playgroud)
您可以尝试将“imageResource”定义为ImageSource
而不是Image
. 这对我有用。
<r:RibbonWindow
x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:r="clr-namespace:Microsoft.Windows.Controls.Ribbon;assembly=RibbonControlsLibrary"
xmlns:pc="clr-namespace:System.Windows.Media;assembly=PresentationCore">
<Grid>
<Grid.Resources>
<pc:ImageSource x:Key="imageSource">your_image.png</pc:ImageSource>
</Grid.Resources>
<r:Ribbon>
<r:RibbonMenuButton
IsEnabled="{Binding ForegroundIsConfigurable}"
SmallImageSource="{DynamicResource imageSource}">
</r:RibbonMenuButton>
</r:Ribbon>
</Grid>
</r:RibbonWindow>
Run Code Online (Sandbox Code Playgroud)
此外,您还可以使用 ElementName 绑定来设置 RibbonMenuButton 的 DataContext,而无需重写 IsEnabled,如下所示。
<r:RibbonWindow x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:r="clr-namespace:Microsoft.Windows.Controls.Ribbon;assembly=RibbonControlsLibrary"
Title="MainWindow" Height="350" Width="525">
<Grid x:Name="root">
<Grid.Resources>
<Image x:Key="imageSource" Source="{Binding myImageSource}"/>
</Grid.Resources>
<r:Ribbon>
<r:RibbonMenuButton DataContext="{DynamicResource imageSource}"
IsEnabled="{Binding ElementName=Root, Path=DataContext.ForegroundIsConfigurable}"
SmallImageSource="{Binding Source}"/>
</r:Ribbon>
</Grid>
</r:RibbonWindow>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2853 次 |
最近记录: |