Can someone please shed some light on this error?
At first I thought SelectedIndex is probably just not a DependencyProperty and cannot be bound, but I was wrong.
If I use a normal binding instead of the markup extension src:ValidatedBinding
, or if I keep the markup extension but bind SelectedItem
instead of SelectedIndex
, then it works.
Here is a small app to demonstrate the problem.
The main window:
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:src="clr-namespace:WpfApplication2"
Title="MainWindow"
Height="350"
Width="525"
>
<ComboBox SelectedIndex="{src:ValidatedBinding SelectedIndex}"
VerticalAlignment="Center" HorizontalAlignment="Center" Width="100">
<ComboBoxItem>Not Specified</ComboBoxItem>
<ComboBoxItem>First</ComboBoxItem>
<ComboBoxItem>Second</ComboBoxItem>
</ComboBox>
</Window>
The code behind the main window:
using System.Windows;
namespace WpfApplication2
{
/// <summary>
/// The main window.
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new Item { Description = "Item 1", SelectedIndex = 0 };
}
}
/// <summary>
/// An object with a string and an int property.
/// </summary>
public sealed class Item
{
int _selectedIndex;
string _description;
public string Description
{
get { return _description; }
set { _description = value; }
}
public int SelectedIndex
{
get { return _selectedIndex; }
set { _selectedIndex = value; }
}
}
}
The code for the markup extension:
using System;
using System.Windows;
using System.Windows.Data;
using System.Windows.Markup;
namespace WpfApplication2
{
/// <summary>
/// Creates a normal Binding but defaults NotifyOnValidationError and
/// ValidatesOnExceptions to True, Mode to TwoWay and UpdateSourceTrigger
/// to LostFocus.
/// </summary>
[MarkupExtensionReturnType(typeof(Binding))]
public sealed class ValidatedBinding : MarkupExtension
{
public ValidatedBinding(string path)
{
Mode = BindingMode.TwoWay;
UpdateSourceTrigger = UpdateSourceTrigger.LostFocus;
Path = path;
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
var Target = (IProvideValueTarget)serviceProvider.GetService(typeof(IProvideValueTarget));
/* on combo boxes, use an immediate update and validation */
DependencyProperty DP = Target.TargetProperty as DependencyProperty;
if (DP != null && DP.OwnerType == typeof(System.Windows.Controls.Primitives.Selector)
&& UpdateSourceTrigger == UpdateSourceTrigger.LostFocus) {
UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
}
return new Binding(Path) {
Converter = this.Converter,
ConverterParameter = this.ConverterParameter,
ElementName = this.ElementName,
FallbackValue = this.FallbackValue,
Mode = this.Mode,
NotifyOnValidationError = true,
StringFormat = this.StringFormat,
ValidatesOnExceptions = true,
UpdateSourceTrigger = this.UpdateSourceTrigger
};
}
public IValueConverter Converter { get; set; }
public object ConverterParameter { get; set; }
public string ElementName { get; set; }
public object FallbackValue { get; set; }
public BindingMode Mode { get; set; }
[ConstructorArgument("path")]
public string Path { get; set; }
public string StringFormat { get; set; }
public UpdateSourceTrigger UpdateSourceTrigger { get; set; }
}
}
The exception when I run this application:
System.Windows.Markup.XamlParseException occurred
HResult=-2146233087 Message='Set property 'System.Windows.Controls.Primitives.Selector.SelectedIndex' threw an exception.' Line number '9' and line position '19'.
Source=PresentationFramework LineNumber=9 LinePosition=19
StackTrace: at System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri) at System.Windows.Markup.WpfXamlLoader.LoadBaml(XamlReader xamlReader, Boolean skipJournaledProperties, Object rootObject, XamlAccessLevel accessLevel, Uri baseUri) at System.Windows.Markup.XamlReader.LoadBaml(Stream stream, ParserContext parserContext, Object parent, Boolean closeStream) at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator) at WpfApplication2.MainWindow.InitializeComponent() in c:\Users\Administrator\Documents\Visual Studio 2012\Projects\WpfApplication2\MainWindow.xaml:line 1 at WpfApplication2.MainWindow..ctor() in c:\Users\Administrator\Documents\Visual Studio 2012\Projects\WpfApplication2\MainWindow.xaml.cs:line 12
InnerException: System.ArgumentException HResult=-2147024809 Message='System.Windows.Data.Binding' is not a valid value for property 'SelectedIndex'. Source=WindowsBase StackTrace: at System.Windows.DependencyObject.SetValueCommon(DependencyProperty dp, Object value, PropertyMetadata metadata, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, OperationType operationType, Boolean isInternal) at System.Windows.DependencyObject.SetValue(DependencyProperty dp, Object value) at System.Windows.Baml2006.WpfMemberInvoker.SetValue(Object instance, Object value) at MS.Internal.Xaml.Runtime.ClrObjectRuntime.SetValue(XamlMember member, Object obj, Object value) at MS.Internal.Xaml.Runtime.ClrObjectRuntime.SetValue(Object inst, XamlMember property, Object value) InnerException:
SelectedIndex
is anint
. You can't put aSystem.Windows.Data.Binding
inside anint
property. YourMarkupExtension
is wrong. You're returning theBinding
itself instead of evaluating it and returning theBinding Source
. – Federico Berasategui{Binding xxx}
is not anint
either. I don't understand. If I were to use{Binding SelectedIndex}
instead of{src:ValidatedBinding SelectedIndex}
then it would work, and essentially both return a binding. Where am I missing the boat? – Martin LotteringBinding
markup extension does not return aBinding
instance, it creates the binding and returns the value in the other end (the Source) – Federico BerasateguiSelectedItem
. DoesSelectedItem
disregard the binding and assign the value instead? – Martin LotteringSelectedItem
is of typeobject
, that's why you're not getting an exception, but that doesn't mean it's working. It's not, you're just assigning an instance of theBinding
class to theSelectedItem
property. – Federico Berasategui