【发布时间】:2014-06-27 12:43:24
【问题描述】:
我有一个用户 WPF UserControl,它只是一个包含图像的网格,我将图像投标到名为 Source 的 ImageSource 依赖属性。
<UserControl x:Class="ImageOnlyClient.MyImage"
x:Name="MyImageControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid Name="MainGrid">
<Border Name="MyImageBorder" BorderThickness="2" BorderBrush="Orange">
<Image Name="MyImage" VerticalAlignment="Top" Opacity="1"
RenderOptions.BitmapScalingMode="NearestNeighbor"
Source="{Binding Path=Source, Mode=OneWay}" />
</Border>
</Grid>
在 UserControl 代码隐藏中,我的类定义如下:
public partial class MyImage : UserControl
{
public ImageSource Source
{
get { return (ImageSource)GetValue(SourceProperty); }
set { SetValue(SourceProperty, value); }
}
#region Source DependencyProperty
public static readonly DependencyProperty SourceProperty;
private static void SourceProperty_PropertyChanged(DependencyObject dobj, DependencyPropertyChangedEventArgs e)
{
//To be called whenever the DP is changed.
System.Diagnostics.Debug.WriteLine("SourceProperty changed is fired");
}
private static bool SourceProperty_Validate(object Value)
{
//Custom validation block which takes in the value of DP
//Returns true / false based on success / failure of the validation
//MessageBox.Show(string.Format("DataValidation is Fired : Value {0}", Value));
return true;
}
private static object SourceProperty_CoerceValue(DependencyObject dobj, object Value)
{
//called whenever dependency property value is reevaluated. The return value is the
//latest value set to the dependency property
//MessageBox.Show(string.Format("CoerceValue is fired : Value {0}", Value));
return Value;
}
#endregion
static MyImage()
{
SourceProperty = DependencyProperty.Register("Source", typeof(ImageSource), typeof(MyImage),
new FrameworkPropertyMetadata(null,
FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.Journal,
new PropertyChangedCallback(SourceProperty_PropertyChanged),
new CoerceValueCallback(SourceProperty_CoerceValue),
false, UpdateSourceTrigger.PropertyChanged),
new ValidateValueCallback(SourceProperty_Validate));
}
public MyImage()
{
InitializeComponent();
}
}
在窗口中,我尝试按如下方式使用 Image,并将其源属性绑定到 WritableBitmap (MyClient.ImageMgr.ImageSource),我可以成功地将其绑定到常规 Image 控件。
<local:MyImage x:Name="imgPrimaryImage" Height="768" Width="1024" Grid.Column="1" Grid.RowSpan="2"
Source="{Binding Path=MyClient.ImageMgr.ImageSource}" />
对于这里发生的事情的任何帮助将不胜感激。我收到以下绑定错误:
System.Windows.Data 错误:40:BindingExpression 路径错误:在“对象”“ImageOnly”(名称=“”)上找不到“源”属性。绑定表达式:路径=源; DataItem='ImageOnly' (Name='');目标元素是“图像”(名称=“我的图像”);目标属性是'Source'(类型'ImageSource')
【问题讨论】:
-
ImageOnly 是我使用 UserControl 的测试窗口的类的名称
标签: c# wpf xaml user-controls