The app used to work fine, but a few weeks ago we updated hundreds of NuGet packages. We recently discovered that any reference to a WPF Behavior gives the following error:
System.Windows.Markup.XamlParseException: ''Add value to collection of
type 'Microsoft.Xaml.Behaviors.BehaviorCollection' threw an
exception.' Line number '78' and line position '86'.'
Inner Exception ArgumentException: Cannot add instance of type
'TextBoxInputBehavior' to a collection of type 'BehaviorCollection'.
Only items of type 'T' are allowed.
I suspect this is because of a NuGet update, but I don't know which one had caused the error, or which need to be changed. I'm using the latest version for Microsoft.Xaml.Behaviors.Wpf (1.1.31).
I would appreciate advice. Thanks.
Code:
xmlns:Behaviors="clr-namespace:MyCompany.MyProject"
xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
<TextBox Text="...">
<i:Interaction.Behaviors>
<Behaviors:TextBoxInputBehavior InputMode="DecimalInput" JustPositiveDecimalInput="False" RangeMin="-1000000.000" RangeMax="1000000.000" />
</i:Interaction.Behaviors>
</TextBox>
//...
using Microsoft.Xaml.Behaviors;
//...
public class TextBoxInputBehavior : Behavior<TextBox>
//...
Related
<ListBox ItemsSource="{Binding Path=Commands}" DisplayMemberPath="Name"/>
DisplayMemberPath doesn't work, and ListBox shows default ToString result of the Commands collection members. Is it possible to debug this, for example, by printing some information to Output window?
Visual Studio 2010, WPF application project. Binding is successful, and I see all members of the Commandscollection. But display is wrong.
Additional information. If I change Path=Commands to non-existing Path=Commands1, I see error messages in the Output window. But there is no any information about error in DisplayMemberPath.
One of the clearer/cleaner ways I've come across for debugging binding errors in WPF is often linked (but using an older, broken link) and can currently be found here: http://www.zagstudio.com/blog/486#.UhyT8fNwbs0
Specifically, the approach that uses a debugging feature introduced in .Net 3.5, using the attached property PresentationTraceSources.TraceLevel and allows you to specify a particular trace level to investigate your binding issues.
Summarising here:
You add the following namespace:
<Window
<!-- Window Code -->
xmlns:diagnostics="clr-namespace:System.Diagnostics;assembly=WindowsBase"
/>
And in your binding expression, set the attached property. In my example, I'm using a list of Cars objects with a Name property, and have incorrectly listed the DisplayMemberPath as Names:
<ListBox ItemsSource="{Binding Path=Cars, diagnostics:PresentationTraceSources.TraceLevel=High}" DisplayMemberPath="Names" />
This results in the following message in the Output window (occurring multiple times, one for each failed binding):
System.Windows.Data Error: 40 : BindingExpression path error: 'Names' property not found on 'object' ''Car' (HashCode=59988153)'. BindingExpression:Path=Names; DataItem='Car' (HashCode=59988153); target element is 'TextBlock' (Name=''); target property is 'Text' (type 'String')
The whole link is worth a read, but that's the gist of a particular technique I had success with (in case the link dies).
DisplayMemberPath does work... are you sure that you're using it correctly? You can find an example of it on the ItemsControl.DisplayMemberPath Property page at MSDN. For your example code to work, you would need to have a public Name property on the data type in the Commands object.
Failing that, WPF errors generally get output into the Visual Studio Output window. If you do not see any errors there, check that you have the options set correctly:
Go to Tools > Options > Debugging tab > Output Window > WPF Trace Settings
You should have at least one of these options (like Data Binding) set to either Warning, Error, All, Critical or Verbose to receive error information.
if you want to use Property "Name" of your "Commands" Item, plese use the following
<ListBox ItemsSource="{Binding Path=Commands}" SelectedItem="{Binding SelectedCommandsItem, Mode=TwoWay}" DisplayMemberPath="Name"/>
Where SelectedCommandsItem is a property of your model that strictly defines a type of the collection items
(Disclaimer: This exception has been reported in numerous other threads, and yes, I have Googled around, trying to find a solution to my issue !!)
I have a WPF application, with a WPF Toolkit DatePicker control bound to a DateTime variable:
<UserControl x:Class="MikesApp.View.UserControls.FXRatesUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:toolkit="clr-namespace:Microsoft.Windows.Controls;assembly=WPFToolkit">
<toolkit:DatePicker x:Name="fxDate" VerticalAlignment="Center"
Text="{Binding Selected_FXRate_Date, Mode=TwoWay}"
Style="{DynamicResource DatePickerStyle1}" >
</toolkit:DatePicker>
Whenever I enter a date, such as 4/20/2012, the DatePicker control seems to think it's actually in UK date format (dd/MM/yyyy), and the WPFtoolkit source code throws an exception of "String was not recognised as a valid DateTime."
This abruptly stops any chance of WPF performing change notifications to other parts of the app, which need to know when this date changes.
Screenshot of VS2010 exception
I'm baffled.
My laptop is setup to display dates in the form MM/dd/yyyy, and I've specifically tried telling my app to use this US date format, first using this code:
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");
Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern = "MMM-dd-yyyy";
Thread.CurrentThread.CurrentCulture.DateTimeFormat.LongDatePattern = "MMM-dd-yyyy hh:mm:ss";
Then, out of desperation, using this code:
CultureInfo ci = new CultureInfo("en-US");
ci.DateTimeFormat.SetAllDateTimePatterns(new string[] { "MM/dd/yyyy" }, 'd' );
Thread.CurrentThread.CurrentCulture = ci;
Thread.CurrentThread.CurrentUICulture = ci;
But regardless of what I try, the DatePicker throws an exception whenever I choose a date which can't be parsed using dd/MMM/yyyy.
If I look at the line of code (taken from DatePicker.cs in the WPF Toolkit SDK) which throws the exception:
newSelectedDate = DateTime.Parse(text, DateTimeHelper.GetDateFormat(DateTimeHelper.GetCulture(this)));
..I've found that "DateTimeHelper.GetCulture(this)" does correctly return "en-US", but that the GetDateFormat function is getting the WRONG date format. It's somehow returning dd/MMM/yyyy, rather than MMM/dd/yyyy.
GetDateFormat's return values
I'm really confused.
I've even tried cut'n'pasting the GetDateFormat function (taken from the following path in the WPFtoolkit source code) into my app, and tried to get it to reproduce the "wrong date format" problem... but when it's in my code, it runs fine, and parses MMM/dd/yyyy dates correctly every time.
WPFtoolkit\Calendar\Microsoft\Windows\Controls\DateTimeHelper.cs
Why would the WPFtoolkit code have a different Culture to my WPF application's code, which uses it ?
And how can I get the WPFtoolkit to use the correct Culture ?
I know this is not directly an answer, but just in case it might help, do you have access to telerik tools? Their RadDateTimePicker has Culture dependency property (of type CultureInfo) that you can set/enforce:
<telerik:RadDateTimePicker x:Name="fxDate" VerticalAlignment="Center"
Culture ="{Binding Culture}"
Text="{Binding Selected_FXRate_Date, Mode=TwoWay}"
Style="{DynamicResource DatePickerStyle1}" >
Also, I am pretty sure you'll say "Of course not", but just in case, are you doing anything like overriding the Template in your DatePickerStyle1 that might throw the TemplateBinding off?
I have this ComboBox
<ComboBox Name="company" Width="120"
HorizontalAlignment="Right" Margin="5"
IsSynchronizedWithCurrentItem="True"
ItemsPanel="{DynamicResource Virtualized}"
ItemsSource="{x:Static local:Repository.Customers}"
SelectedItem="{Binding Path=SelectedCustomer}"
DisplayMemberPath="CM_FULL_NAME""/>
It runs. It works. Except in the designer, which won't let me do anything because of the error:
ArgumentException was thrown on "StaticExtention": Exception has been thrown by the target of an invocation.
Detail
The specified named connection is either not found in the configuration, not intended to be used with the EntityClient provider, or not valid.
I have tried several things in the static class to skip the constructor in designtime, none of which fix the error:
if (LicenseManager.UsageMode == LicenseUsageMode.DesignTime)
if (DesignerProperties.GetIsInDesignMode(this))
if (System.Reflection.Assembly.GetExecutingAssembly().Location.Contains("VisualStudio"))
And returning in the constructor if any of these are true. Still getting the error.
Edit: Not sure if it makes any difference, but the static repository class uses EF4 to get from a database.
Edit2: Also tried ItemsSource {Binding} to the static lists, still get the same error. Note, calling it a repository is a misnomer, the lists are loaded on startup and never changed. Below answer does not work, still trying to figure this out.
Edit3: Thomas' Suggestion to debug design mode wasn't doable. I am using VS2010 Express, and the tools menu does not have an attach to process option. I still don't know why this breaks the designer and works in runtime.
In the getter of the Customers property, try to add this code:
if (DesignerProperties.GetIsInDesignMode(new DependencyObject()))
return null;
Thomas answer:
if (DesignerProperties.GetIsInDesignMode(new DependencyObject()))
return null;
Works in the static constructor.
I've just installed IronPython 2.7 with VS support, and am trying to create a simple prototype WPF application. Something is broken, probably in my installation, and I can't figure out how to diagnose it. I can't get the simplest of bindings to work; they fail with an exception that seems really, really wrong.
I create a WPF application project, and put XAML like this in my WpfApplication1.xaml file:
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="WpfApplication1">
<Grid>
<TextBox x:Name="MyTextBox" Text="{Binding RelativeSource={RelativeSource Self}, Mode=OneWay, Path=ActualWidth}"/>
</Grid>
</Window>
When I run this, I get this exception:
System.Xaml.XamlObjectWriterException was unhandled by user code
Message=Provide value on 'System.Windows.Data.Binding' threw an exception.
InnerException: System.Windows.Markup.XamlParseException
Message=A 'Binding' cannot be set on the 'Text' property of type 'TextBox'. A 'Binding' can only be set on a DependencyProperty of a DependencyObject.
Hmm, last time I looked, Text is a dependency property. And indeed, if I create the binding in code, it works:
import clr
clr.AddReference('PresentationFramework')
from System.Windows import Application, Window, Controls, Data, PropertyPath
class MyWindow(Window):
def __init__(self):
clr.LoadComponent('WpfApplication1.xaml', self)
t = self.FindName("MyTextBox")
b = Data.Binding()
b.RelativeSource = Data.RelativeSource.Self
b.Mode = Data.BindingMode.OneWay
b.Path=PropertyPath("ActualWidth")
t.SetBinding(Controls.TextBox.TextProperty, b)
I'm pretty baffled at this point. It's hard for me to imagine anything that could cause this problem that wouldn't also mess up creating WPF objects from XAML completely. Is there something obvious that I'm missing?
This is a bug in the new WPF support. It's fixed in the current sources and so it will be fixed in the Beta 1 release. The underlying cause is that there are "schema contexts" which need to be used to get full WPF semantics that we weren't using before. It also moves to a new "wpf" module instead of being in the clr module.
Whenever I try to reference the following namespace in my XAML, the code compiles and the project starts, but the InitializeComponent method throws an error. Here's the XAML reference:
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
and here's the use of ExtendedVisualStateManager
<ei:ExtendedVisualStateManager/>
The error is this:
The type 'ExtendedVisualStateManager' was not found because 'http://schemas.microsoft.com/expression/2010/interactions' is an unknown namespace. [Line: 19 Position: 37]
Is there a new namespace I need to use to use this control?
Here are some facts.
The Microsoft.Expression.Interactions.dll version 4.0.5.0 contains the namespace Microsoft.Expression.Interactivity.Core.
This Microsoft.Expression.Interactivity.Core contains the type ExtendedVisualStateManager.
The Microsoft.Expression.Interactions.dll version 4.0.5.0 carries a XmlnsDefinition that maps the URL "http://schemas.microsoft.com/expression/2010/interactions" to the namespace Microsoft.Expression.Interactivity.Core.
Hence a project referencing version 4.0.5.0 of Microsoft.Expression.Interactions.dll can contain Xaml using xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions" that can then contain ei:ExtendedVisualStateManager.
You'll note I've repeated the version number a few times. If you do have an interactions dll referenced in a Silverlight 4 project but your code doesn't work then perhaps its the wrong version. However in that case Dan's answer should still have worked.
Make sure your Silverlight application has a reference to the Microsoft.Expression.Interactions assembly.
<UserControl
xmlns:ei="clr-namespace:Microsoft.Expression.Interactivity.Core;assembly=Microsoft.Expression.Interactions"
...other namespaces... />
<VisualStateManager.CustomVisualStateManager>
<ei:ExtendedVisualStateManager/>
</VisualStateManager.CustomVisualStateManager>
</UserControl>
I had everything correct per the other answers and like you, the problem still existed. It was failing at runtime on a usercontrol in my project (and that project did reference Microsoft.Expression.Interactions).
However, that usercontrol was being used on a form in another project. Once I added the reference to Microsoft.Expression.Interactions to the outer project, the runtime error was solved. I was not loading assemblies dynamically and so I'm not 100% certain why this was a problem.
I think you should look in your project's properties. Find the references (Microsoft.Expression.Interactions or/and other "Expression" assemblies you may use, and set the "Copy Local" property to TRUE and try it again.
None of the answers solved this puzzling problem to me.
Apparently I needed Microsoft Expression Blend SDK for Silverlight 4.
Installing it has solved the issue.