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.
Related
I have the following code:
ProcessMainWindow.xaml.cs
public ProcessMainWindow(SourceTableRowInfo rowContent)
{
InitializeComponent();
this.DataContext = rowContent;
}
ProcessMainWindow.xaml
<!--Insert Code---->
<TabItem x:Name="postProcessTab" Header="Post-Processes">
<local:PostProcessUserControl PostProcessItem="{Binding PostProcess, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
</TabItem>
So RowContent has an element called PostProcess in it. I am trying to bind that element to a UserControl Dependency Property, but cannot get the binding to work. Based off what I was reading here (Using the DataContext) my understanding is that what I have should work, but I can't get it to work. So am I misunderstanding what it is saying? I have read a few other pages but still can't figure it out.
I have also tried:
<!--Insert Code---->
<TabItem x:Name="postProcessTab" Header="Post-Processes">
<local:PostProcessUserControl PostProcessItem="{Binding, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, Path=PreProcess}" />
</TabItem>
If these are correct, I guess I have an error elsewhere in my code. I have yet to fully understand data binding in WPF to know if that is the case though so any help would be appreciated.
One thing to try is to put a trace on the Binding:
PostProcessItem="{Binding PostProcess, PresentationTraceSources.TraceLevel=High}.
Then look for what it tells you at runtime in the Output pane in VS. This can help you identify cases where your DataContext isn't what you think it is, or your Path is misspelled -- all the simple stuff that the compiler catches in C# but can't be detected at compile time in a late-binding/duck-typed miasma like XAML.
Don't leave those traces on bindings once you're done with them; they can really slow things down. Or at least set TraceLevel=None, to save trouble if think you'll be coming back to one later.
We have an application that throws an UpdateRegionsException while launching. We suspect it has to do with a DataContext not being set properly in our XAML. Has anyone come across this type of problem before?
It seems as though there's a bug with elements such as Checkbox, and DatePicker, and perhaps others. On some cases I'm forced to put the DataContext prefix to my property name. For example,
IsEnabled="{Binding DataContext.TransferOriginalRxInformationNeverFilled, Converter={StaticResource InvertBooleanConverter}}"
If I don't put the DataContext prefix to the binding, the application shuts down during startup giving the following exception:
Microsoft.Practices.Prism.Regions.UpdateRegionsException: An exception occurred while trying to create region objects.
Hope this helps anyone in the future.
All,
I'm using DataBase First Entity Framework v4.4. In the DB (and data model) is Table1 that has a 1:many relationship to Table2.
I am binding a DataGrid in WPF to Table1.Local.First().Table2 (for simplicity, assume that there is an entity in Table1.Local to begin with).
ViewModel:
Public SomeEntityDBContextWithTable1AndTable2 Container { get; set; }
Public ICollection Table2ToDisplay { get { return Container.Table1.Local.First().Table2; } } //Note: :Many navigation properties return ICollection<T>, but the object type is of ObservableCollection<T>.
In XAML, I have the following
<GroupBox Header=Table2 DataContext="{Binding Path=Table2ToDisplay, UpdateSourceTrigger=PropertyChanged}">
<DataGrid ItemsSource="{Binding}" AutoGenerateColumns="False" CanUserAddRows="True">
<DataGrid.Columns>
<!--A bunch of columns-->
</DataGrid.Columns>
</DataGrid>
</GroupBox>
When clicking inside a NewItemPlaceHolder that happens to be a text box, I get the System.InvalidOperationException occuring in PresentationFramework.dll. This doesn't crash my application, but I see it in the Output. My guess is that entities are added on another thread, and thus CollectionChanged event fires on another thread, and this causes the InvalidOperationException. However, since the code is mainly done via XML, I can't seem to find a way to handle this exception (or is it already being handled, it's just that it is being reported to Output). Is there a safe way to use CanUserAddRows="True" with EntityFramework where ":Many" navigation properties are of type ObservableCollection?
I should point out that I have also tried wrapping my Table2ToDisplay property inside a CollectionViewSource, but I still see the InvalidOperationException in the output.
Thanks in advance.
I'm going to take a wild guess since not all the details are present (update code, stack trace, etc) that you are changing the bound collection in a non-ui thread.
In which case, you need:
(in update logic)
Application.Current.Dispatcher.Invoke((Action)(() =>
{
// update collection here
});
Okay. Changing Visual Studio's debugger to stop at all exceptions lead me to some insite. The exception was "NewItemPlaceHolder is not allowed during an AddNew...", which occured because of a PropertyChanged event on my Entity. Turns out this exception was already being handled, so I think I'm good.
I'm getting an "Object reference not set to an instance of an object" error when I try to reload the Designer for my XAML UserControl. Visual Studio highlights the following line as being the problem:
<local:TemplateDetail Grid.Row="2" Grid.Column="1" Grid.ColumnSpan="3"
Width="600" TemplateData="{Binding ElementName=cbo_templates,
Path=SelectedItem.Data, Mode=OneWay}"/>
TemplateDetail is another UserControl. When I view TemplateDetail, its Designer view loads just fine, so I don't think there's a problem there. There is a ComboBox in my XAML named cbo_templates that contains instances of my Template class, which has a Data property (hence SelectedItem.Data). However, if I remove .Data from the Path in the above XAML, I still get the "Object reference" error, so I don't think the problem is that I'm trying to access the Path property on null. Here's my ComboBox XAML just in case:
<ComboBox ItemsSource="{Binding Path=List}" Grid.Row="1" Grid.Column="3"
VerticalAlignment="Center" x:Name="cbo_templates" Width="250"
HorizontalAlignment="Left" DisplayMemberPath="Name"
SelectedValuePath="Name" SelectedIndex="0"/>
Getting this error is a real problem because the Design view won't load, so I can't see what my UserControl looks like without running the app. Any idea what could be wrong? It builds fine and I don't see any binding problems in the Build Output.
Edit: here is the constructor code for both UserControls:
Constructor of UserControl with "Object reference" error:
InitializeComponent();
grd_templateList.DataContext = this; // refers to containing <Grid> in XAML
Constructor of UserControl I'm trying to embed, the one whose Design view loads okay:
InitializeComponent();
grd_templateDetail.DataContext = this; // refers to containing <Grid> in XAML
Edit: I tried putting an if (null != grd_templateList) check in the constructors before setting their DataContext properties, but that didn't help--still getting the "Object reference" error when reloading the Designer.
Edit: the List property that the ComboBox uses is a DependencyProperty. I have a default value set in the Register method:
public static readonly DependencyProperty ListProperty =
DependencyProperty.Register(
"List",
typeof(List<Template>),
typeof(TemplateList),
new PropertyMetadata(
new List<Template> { _defaultTemplate }
)
);
Even if I try to initialize List in the constructor for my UserControl, I still get the error when reloading the Designer. I don't think the problem is that List is null or SelectedItem.Data is a bad path.
Edit: okay, even just having this causes my Designer to not load, giving the "Object reference" error:
<local:TemplateDetail Grid.Row="2" Grid.Column="1" Grid.ColumnSpan="3"
TemplateData="{Binding}"/>
There is something it dislikes about the TemplateData property being bound, apparently.
Edit: to add to the mystery, I can view the Design view of my overall/main Window, which includes the UserControl whose Design view gives me the "Object reference" error. O_o
What Alex says is the way to go. But I think its a little confusing to understand what he is saying.
Assuming you have your project open in Visual Studio, open another Visual Studio instance and select Debug->Attach To Process. In the dialog which opens select
XDesProc.exe (which is the XAML UI Designer) for VS2012 and newer or
devenv.exe for older VS versions.
Then do "Reload Designer" for the user control and see the output in the second VS instance to check what exactly is the error.
If you have 'Object reference not set to an instance of an object' in XAML, but your application compiles and runs fine, you will usually find out that its cause is something in a constructor that can't be resolved at design time.
While you can find out the root of the problem with the help of other answers to this question, sometimes that is something you can't simply fix, you need it in your code exactly as you have it, but you don't want to see this error.
In this case, just click the "Disable project code" button located on the bottom of your designer view and Visual Studio designer will stop trying to construct an instance to provide design time data view.
See here for detailed information.
It's probably something in the constructor of your user controls. VS2008 WPF designer appears have some issues with this.
In a project we took over, we added:
if (System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
{
return;
}
to the beginning of the constructor of the user controls where this happens to avoid that error.
If your user control throws exception at design time, you can debug it. To do this, open Dll project with this user control in Visual Studio. Select another Visual Studio instance as executable for debugging. Start debugging. In the second (debugged) Visual Studio instance use your user control in the client XAML page. By this way, you can debug user control in design mode.
This thread is a little old, but I had a problem I just solved with its help, so I may be able to slightly clarify some points.
Have your solution loaded in Visual Studio as usual.
Open a 2nd instance of VS, menu debug/attach to process/select devenv.
You should see nothing spectacular! In VS 2010, i just get
"Disassembly cannot be displayed in run mode."
Go back to your 1st instance, where your solution is opened. Load or reload the offending XAML
file. If you have a problem (I had an exception on a user control, so I could not load that window), the debugger should point the offending code in the 2nd instance. in my case, it was very
clear and obvious.
To prevent the offending code from running at design time, I used
If System.ComponentModel.LicenseUsageMode.Runtime = 1 Then
myObject = New ObjectDefinition
End If
Works perfectly well.
In Visual Studio 2015 for WPF:
Hover with your mouse over the "Object reference not set to an instance of an object" in the Design view.
Wait a (few) second(s) and you will see a popup
Select "View Exception Details" (you will also see "View Code" and "Delete this element"
This dialog will show you the exception and the StackTrace
Hope this helps.
If you do this on the XAML you will just see the exception but not the popup with "View Exception Details", thus you need to do it in the Designer/Design view.
I was able to solve the problem after giving a name to an object. It is VS2015, and my markup is different, but it could help somebody too:
<ResourceDictionary>
<DataTemplate x:Key="ThisKeySolvesDesignersNullRef"
DataType="local:MyViewModel">
<local:MyControl/>
</DataTemplate>
</ResourceDictionary>
I was having this error today after editing a lot of XAML in my UWP code and I couldn't figure out what was wrong... but after some close inspection, I noticed this mistake I had made:
<Button Click="{Binding MyCommand}" />
I assigned my Command to the Click handler by mistake, and that resulted in a null reference exception... After changing Click to Command, the error went away.
XAML error reporting needs to be improved!
I just had this problem with VS2022 (17.3.3). I tried to attach from another instance of VS but it never came up with the exception. I tried everything I could find such as handling the design case of the constructor and clearing out the .vs directory. Nothing helped. Finally I tried to run the application. The error didn't show when running. After running, the issue seems to be gone now. Even when I close and reopen the solution I don't see it anymore.
I have a silverlight page in which I am loading a control. This control has its own viewmodel which I pass in to the .xaml.cs file thru its constructor. However I get an error when compiling. This is the error:
{No matching constructor found on type 'MySite.Views.SearchFlyOutWin'}
My main page makes a reference to the 'SearchFlyOutWin' like this
xmlns:part="clr-namespace:MySite.Views;assembly=MySite"
In my mainpage.xaml I have tried to load the control like this
<part:SearchFlyOutWin x:Name="searchFlyOutWin" Visibility="{Binding Converter={StaticResource BooleanToVisibilityConverter}, Path=IsSearchVisible}" />
The constructor in my SearchFlyOutWin.xaml.cs is like this
public SearchFlyOutWin(ISearchFlyoutViewModel viewmodel)
{
InitializeComponent();
DataContext = viewmodel;
}
I get the error described above in my Mainpage.xaml.cs when it calls the InitializeComponent(); method.
I think I probably need to direct the clr to call the correct constructor when loading the searchwin in this line here below
<part:SearchFlyOutWin x:Name="searchFlyOutWin" Visibility="{Binding Converter={StaticResource BooleanToVisibilityConverter}, Path=IsSearchVisible}" />
Any ideas on how to correct this? ...Thanks for your time.
.
I have a silverlight page in which I
am loading a control. This control has
its own viewmodel which I pass in to
the .xaml.cs file thru its
constructor. However I get an error
when compiling. This is the error:
{No matching constructor found on type
'MySite.Views.SearchFlyOutWin'}
If your own control's constructor takes some parameter(s), then you cannot use this control in XAML. In XAML, every control must have a constructor with no parameter. That is why, it shows the error message {No matching constructor found on type 'MySite.Views.SearchFlyOutWin'}, since XAML parser searches a constructor with no parameter in your control called SearchFlyOutWin, and it found none!
One soution is that remove the parameter from constructor, and define your Model in the XAML as resource, then set the DataContext to it. Like this,
<Window.Resources>
<local:SearchFlyoutViewModel x:Key="model"/>
</Window.Resources>
<part:SearchFlyOutWin DataContext="{StaticResource model}"/>
Hope, it solves your problem.
.
If you're committed to passing the viewmodel to the object in the constructor (which I don't think is a bad thing), the only way I've found to do this is to create the object in code and then add it to its parent panel programatically. Setting up bindings in code is also possible, though the syntax is more complex than the XAML syntax. The code might looks something like:
SearchFlyOutWin searchFlyOutWin = new SearchFlyOutWin(viewModel);
Binding b = new Binding("");
b.Source = IsSearchVisible;
b.Converter = new BooleanToVisibilityConverter();
searchFlyOutWin.SetBinding(SearchFlyOutWin.VisibilityProperty, b);
SearchFlyOutWinParentPanel.Children.Add(searchFlyOutWin);
Where SearchFlyOutWinParentPanel is some panel that can accept children. If there's an alternate way to do this in XAML, I'd love to see it, but I haven't found it yet.
You may need to set you viewmodel class to be public.
Because I guess your viewmodel class will be in another namespace other than view.