I have this wierd bug. When I build my project, it always pops up two instances of my singleton window. Here is video of it happening. Though I don't think it will help anyting, here is most of xaml of the window. In code behind are just events for mouse movement and a closing event.
<Window x:Class="Scoreboard.OutputWindow"
d:DataContext="{d:DesignInstance viewModel:ControlPanel}"
Title="OutputWindow" Height="375" Width="540"
Background="{Binding AppData.Settings.Color, Converter={converters:ColorToBrushConverter}}"
MouseLeftButtonDown="football_MouseLeftButtonDown"
MouseLeftButtonUp="football_MouseLeftButtonUp"
MouseMove="football_MouseMove">
<Window.InputBindings>
<KeyBinding Modifiers="Control" Key="F" Command="{Binding FullScreenCommand}" />
</Window.InputBindings>
<Grid ...>
</Grid>
</Window>
This window is a singleton in my ViewModel. I access it just from there. It happens on both of my two PCs.
EDIT:
When I remove it from the ViewModel, it doesn't happen anymore. But I sort of need it there.
EDIT2: Here is new project with that window. It doesn't behave exactly the same, but when you do some changes so it builds on debug, then on sturtup it creates another OutputWindow which isn't caught by breakpoint in constructor.
The root cause of your problem is the following line in your ViewModel:
public ViewModel()
{
OutputWindow.IsEnabled = true;
}
This implicitly creates a new OutputWindow() in the getter of the property:
private OutputWindow _outputWindow;
public OutputWindow OutputWindow =>
_outputWindow ?? (_outputWindow = new OutputWindow { DataContext = this });
The constructor then looks like this:
public OutputWindow()
{
InitializeComponent();
Show();
}
This wouldn't be so bad at the moment but every time your MainWindow is instantiated, a new instance of ViewModel is implicitly created as well because of this code in the MainWindow:
<Window.DataContext>
<local:ViewModel />
</Window.DataContext>
Okay, that explains why the OutputWindow is showing up on start - but why does it show on build?
(Or in my case even if you open the XAML code of MainWindow.xaml in Visual Studio.)
If found the culprit and it's this little gem here which originates from devenv.exe:
TestApplication.exe!TestApplication.OutputWindow.OutputWindow() Line 15
TestApplication.exe!TestApplication.ViewModel.OutputWindow.get() Line 6
TestApplication.exe!TestApplication.ViewModel.ViewModel() Line 10
...
mscorlib.dll!System.Activator.CreateInstance(System.Type type, bool nonPublic)
...
Microsoft.VisualStudio.DesignTools.Platform.dll!Microsoft.VisualStudio.DesignTools.Platform.InstanceBuilders.ClrObjectInstanceBuilder.Instantiate(Microsoft.VisualStudio.DesignTools.Platform.InstanceBuilders.IInstanceBuilderContext context, Microsoft.VisualStudio.DesignTools.Platform.InstanceBuilders.ViewNode viewNode = {Microsoft.VisualStudio.DesignTools.Platform.InstanceBuilders.ViewNode}) Unknown
Microsoft.VisualStudio.DesignTools.Platform.dll!Microsoft.VisualStudio.DesignTools.Platform.InstanceBuilders.ViewNodeManager.CreateInstance(Microsoft.VisualStudio.DesignTools.Platform.InstanceBuilders.IInstanceBuilder builder, Microsoft.VisualStudio.DesignTools.Platform.InstanceBuilders.ViewNode viewNode) Unknown
Microsoft.VisualStudio.DesignTools.Platform.dll!Microsoft.VisualStudio.DesignTools.Platform.InstanceBuilders.ViewNodeManager.Instantiate(Microsoft.VisualStudio.DesignTools.Platform.InstanceBuilders.ViewNode viewNode = {Microsoft.VisualStudio.DesignTools.Platform.InstanceBuilders.ViewNode}) Unknown
...
XDesProc.exe!Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.DesignerProcess.RunApplication()
...
mscorlib.dll!System.Threading.ThreadHelper.ThreadStart()
So, why does it happen?
On build or on open of the XAML designer, Visual Studio starts a thread and instructs XDesProc.exe to create a new instance of your MainWindow.
(XDesProc.exe is the component that is responsible for the XAML designer in Visual Studio and perhaps the designer should refresh if you build a project.)
And from there on, the way is as shown above:
A new ViewModel is created in the implicit DataContext of the MainWindow which implicitly creates a new instance of the OutputWindow in the getter of the property which in turn calls Show() on itself. And voilĂ , there you have your OutputWindow on screen!
In some cases there are even two OutputWindows showing but that's only because the designer (or maybe another component) is called two times.
So, bottom line - what do you need to fix your code?
There are multiple possible solutions.
Most important you should stop the implicit creation of the OutputWindow in the ViewModel. You can achieve this by doing one (or more) of the following:
Remove OutputWindow.IsEnabled = true; in the constructor of ViewModel.
Don't call Show(); in the constructor of OutputWindow.
Don't instantiate your ViewModel implicitly using <Window.DataContext><local:ViewModel />.
I think it's fair to say that it's just plain wrong to implicitly show a window if you just create an instance of a simple ViewModel. So, if you break this unlucky chain of implicit events then your problem will be gone forever.
Related
I created a ViewModel and bound its property to two textboxes on UI. The value of the other textbox changes when I change the value of first and focus out of the textbox but I'm not implementing INotifyPropertyChanged. How is this working?
Following is XAML
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<local:ViewModel />
</Window.DataContext>
<StackPanel>
<TextBox Text="{Binding Name}" />
<TextBox Text="{Binding Name}" />
</StackPanel>
</Window>
And following is my ViewModel
class ViewModel
{
public string Name { get; set; }
}
I tested it, you are right. Now i searched for it on the web, and found this.
Sorry to take so long to reply, actually you are encountering a another hidden aspect of WPF, that's it WPF's data binding engine will data bind to PropertyDescriptor instance which wraps the source property if the source object is a plain CLR object and doesn't implement INotifyPropertyChanged interface. And the data binding engine will try to subscribe to the property changed event through PropertyDescriptor.AddValueChanged() method. And when the target data bound element change the property values, data binding engine will call PropertyDescriptor.SetValue() method to transfer the changed value back to the source property, and it will simultaneously raise ValueChanged event to notify other subscribers (in this instance, the other subscribers will be the TextBlocks within the ListBox.
And if you are implementing INotifyPropertyChanged, you are fully responsible to implement the change notification in every setter of the properties which needs to be data bound to the UI. Otherwise, the change will be not synchronized as you'd expect.
Hope this clears things up a little bit.
So basically you can do this, as long as its a plain CLR object. Pretty neat but totally unexpected - and i have done a bit of WPF work the past years. You never stop learning new things, right?
As suggested by Hasan Khan, here is another link to a pretty interesting article on this subject.
Note this only works when using binding. If you update the values from code, the change won't be notified. [...]
WPF uses the much lighter weight PropertyInfo class when binding. If you explicitly implement INotifyPropertyChanged, all WPF needs to do is call the PropertyInfo.GetValue method to get the latest value. That's quite a bit less work than getting all the descriptors. Descriptors end up costing in the order of 4x the memory of the property info classes. [...]
Implementing INotifyPropertyChanged can be a fair bit of tedious development work. However, you'll need to weigh that work against the runtime footprint (memory and CPU) of your WPF application. Implementing INPC yourself will save runtime CPU and memory.
Edit:
Updating this, since i still get comments and upvotes now and then from here, so it clearly is still relevant, even thouh i myself have not worked with WPF for quite some time now. However, as mentioned in the comments, be aware that this may cause memory leaks. Its also supposedly heavy on the Reflection usage, which has been mentioned as well.
I just found out that this also works in WinForms, kinda :/
public class Test
{
public bool IsEnabled { get; set; }
}
var test = new Test();
var btn = new Button { Enabled = false, Text = "Button" };
var binding = new Binding("Enabled", test, "IsEnabled");
btn.DataBindings.Add(binding);
var frm = new Form();
frm.Controls.Add(btn);
test.IsEnabled = true;
Application.Run(frm);
Strangely though, this doesn't disable the button:
btn.Enabled = false;
This does:
test.IsEnabled = false;
I can explain why the property is updated when focus changes: all Bindings have an UpdateSourceTrigger property which indicates when the source property will be updated. The default value for this is defined on each DependencyProperty and for the TextBox.Text property is set to LostFocus, meaning that the property will be updated when the control loses focus.
I believe UrbanEsc's answer explains why the value is updated at all
I'm using Caliburn.Micro (CM) in a WPF application with ViewModel-first approach. I'm composing the main view with a command bar and an active item. Main viewModel sets the property for the command bar viewModel, and navigates to active item correctly.
Everything looks fine at runtime, the issue is only related to design-time: the main view shows empty in designer and I cannot find how to set it correctly. I managed to having this working in other scenarios, e.g. when setting the datacontext at design time for a whole Window or UserControl, i.e. when that's the root UI element in XAML. But now I'm not able to to this for child ContentPresenter UI elements within a Window.
This is an excerpt of the main view I'm composing:
<Window x:Class="...MainView" ...>
<DockPanel ...>
<!-- this one binds to a property of type CommandBarViewModel -->
<ContentControl x:Name="CommandBar" ... />
<ContentControl x:Name="ActiveItem" ... />
</DockPanel>
</Window>
I've checked a number of related reads, but none of them seems to fit/solve my issue. This question is basically the same as mine, but has no answers. That has a reference to this other question which it seems to me is going for a View-first approach, judging by the cal:View.Model bindings.
I tried adding a design-time context like the following (fake namespace not shown for brevity):
<ContentControl x:Name="CommandBar" ...
d:DataContext="{d:DesignInstance Type=fake:DesignTimeCommandBarViewModel, IsDesignTimeCreatable=True}"
cal:Bind.AtDesignTime="True"/>
but then I incur in one of two cases:
if DesignTimeCommandBarViewModel inherits from the actual CommandBarViewModel, then I incur in somewhat the usual problem of design-time Vs dependency injection: the default constructor passes null for all injected dependencies, and base constructor or something else gives problem. I mean, it seems it would take some effort to find a workaround for this, and just for design-time support
if DesignTimeCommandBarViewModel does not inherit from the actual viewModel, then it seems that (correctly) the CommandBarView is not instantiated, as now there's no relationship anymore between the viewModel and that view.
Have you got any idea about this? Maybe this should be solved with a design-time version of the hosting MainViewModel?
Other references I checked: this answer, from Rob Eisenberg himself, this CM thread, this other SO
Edit
Following my last (auto-)hint, I'm trying also creating and instantiating a DesignTimeMainViewModel, not inheriting from MainViewModel, which exposes the same properties and sets a DesignTimeCommandBarViewModel in its default constructor. In this case, in place of the command bar the designer shows the classic CM complaint: cannot find view for the DesignTimeCommandBarViewModel.
What's next?
Well, here's the solution I found: I'd be glad to hear about better ways or other suggestions.
Host MainView XAML specifies a design-time data-context pointing to a design-time version of the Main view-model which, by the way, does not inherit from the runtime version MainViewModel. ContentControl items are left untouched.
<Window x:Class="...MainView" ...
d:DataContext="{d:DesignInstance Type=fake:DesignTimeMainPanelViewModel, IsDesignTimeCreatable=True}"
cal:Bind.AtDesignTime="True">
<DockPanel ...>
<ContentControl x:Name="CommandBar" ... />
<ContentControl x:Name="ActiveItem" ... />
</DockPanel>
</Window>
DesignTimeMainPanelViewModel has the same public properties as MainPanelViewModel, has a default c'tor without dependencies and its c'tor sets the CommandBar property to a new instance of DesignTimeCommandBarViewModel:
public class DesignTimeMainPanelViewModel
{
public DesignTimeMainPanelViewModel()
{
CommandBar = new DesignTimeCommandBarViewModel();
ActiveItem = ...some instance here as well...;
}
public DesignTimeCommandBarViewModel CommandBar { get; private set; }
public IScreen ActiveItem { get; private set; }
}
DesignTimeCommandBarViewModel class is decorated with a custom Attribute having only one required parameter, the System.Type of the view associated with that view-model.
During bootstrap the code adds a new ViewLocator strategy to get the view Type from the view-model Type, by setting a new ViewLocator.LocateTypeForModelType.
The new locator function will try to find a view Type if the standard locator function cannot find one. Granted, it will look for the custom attribute on view-model Type, and if found that would be the returned view Type. Here's the gist of that:
Type viewType = _previousLocate(viewModelType, displayLocation, context);
if (viewType == null)
{
FakeViewAttribute fakeViewAttr = Attribute.GetCustomAttribute(viewModelType, typeof(FakeViewAttribute)) as FakeViewAttribute;
if (fakeViewAttr != null) viewType = fakeViewAttr.ViewType;
}
return viewType;
I created a ViewModel and bound its property to two textboxes on UI. The value of the other textbox changes when I change the value of first and focus out of the textbox but I'm not implementing INotifyPropertyChanged. How is this working?
Following is XAML
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<local:ViewModel />
</Window.DataContext>
<StackPanel>
<TextBox Text="{Binding Name}" />
<TextBox Text="{Binding Name}" />
</StackPanel>
</Window>
And following is my ViewModel
class ViewModel
{
public string Name { get; set; }
}
I tested it, you are right. Now i searched for it on the web, and found this.
Sorry to take so long to reply, actually you are encountering a another hidden aspect of WPF, that's it WPF's data binding engine will data bind to PropertyDescriptor instance which wraps the source property if the source object is a plain CLR object and doesn't implement INotifyPropertyChanged interface. And the data binding engine will try to subscribe to the property changed event through PropertyDescriptor.AddValueChanged() method. And when the target data bound element change the property values, data binding engine will call PropertyDescriptor.SetValue() method to transfer the changed value back to the source property, and it will simultaneously raise ValueChanged event to notify other subscribers (in this instance, the other subscribers will be the TextBlocks within the ListBox.
And if you are implementing INotifyPropertyChanged, you are fully responsible to implement the change notification in every setter of the properties which needs to be data bound to the UI. Otherwise, the change will be not synchronized as you'd expect.
Hope this clears things up a little bit.
So basically you can do this, as long as its a plain CLR object. Pretty neat but totally unexpected - and i have done a bit of WPF work the past years. You never stop learning new things, right?
As suggested by Hasan Khan, here is another link to a pretty interesting article on this subject.
Note this only works when using binding. If you update the values from code, the change won't be notified. [...]
WPF uses the much lighter weight PropertyInfo class when binding. If you explicitly implement INotifyPropertyChanged, all WPF needs to do is call the PropertyInfo.GetValue method to get the latest value. That's quite a bit less work than getting all the descriptors. Descriptors end up costing in the order of 4x the memory of the property info classes. [...]
Implementing INotifyPropertyChanged can be a fair bit of tedious development work. However, you'll need to weigh that work against the runtime footprint (memory and CPU) of your WPF application. Implementing INPC yourself will save runtime CPU and memory.
Edit:
Updating this, since i still get comments and upvotes now and then from here, so it clearly is still relevant, even thouh i myself have not worked with WPF for quite some time now. However, as mentioned in the comments, be aware that this may cause memory leaks. Its also supposedly heavy on the Reflection usage, which has been mentioned as well.
I just found out that this also works in WinForms, kinda :/
public class Test
{
public bool IsEnabled { get; set; }
}
var test = new Test();
var btn = new Button { Enabled = false, Text = "Button" };
var binding = new Binding("Enabled", test, "IsEnabled");
btn.DataBindings.Add(binding);
var frm = new Form();
frm.Controls.Add(btn);
test.IsEnabled = true;
Application.Run(frm);
Strangely though, this doesn't disable the button:
btn.Enabled = false;
This does:
test.IsEnabled = false;
I can explain why the property is updated when focus changes: all Bindings have an UpdateSourceTrigger property which indicates when the source property will be updated. The default value for this is defined on each DependencyProperty and for the TextBox.Text property is set to LostFocus, meaning that the property will be updated when the control loses focus.
I believe UrbanEsc's answer explains why the value is updated at all
I'm tryihg to bind a combobox item source to a static resource. I'm oversimplfying my example so that it's easy to understand what i'm doing.
So I have created a class
public class A : ObservableCollection<string>
{
public A()
{
IKBDomainContext Context = new IKBDomainContext();
Context.Load(Context.GetIBOptionsQuery("2C6C1Q"), p =>
{
foreach (var item in SkinContext.IKBOptions)
{
this.Add(item);
}
}, null);
}
}
So the class has a constructor that populates itself using a domaincontext that gets data from a persisted database. I'm only doing reads on this list so dont have to worry about persisting back.
in xaml i add a reference to the namespace of this class then I add it as a usercontrol.resources to the page control.
<UserControl.Resources>
<This:A x:Key="A"/>
</UserControl.Resources>
and then i use it this staticresource to bind it to my combobox items source.in reality i have to use a datatemplate to display this object properly but i wont add that here.
<Combobox ItemsSource="{StaticResource A}"/>
Now when I'm in the designer I get the error:
Cannot Create an Instance of "A".
If i compile and run the code, it runs just fine. This seems to only affect the editing of the xaml page.
What am I doing wrong?
When running in the designer the full application runtime is not available. However the designer doesn't just magically know how to mock the UI of a UserControl. Its Xaml is parsed and the objects described there are instantiated.
Its up to you to code your classes to cope with existence in a designer. You can use the static proeprty DesignerProperties.IsInDesignTool to determine if your code is currently being used in a designer tool or not.
If in a designer you could deliver a set of test data rather than attempt to access a data service.
My problem is same as described above and i alse used DesignerProperties.IsInDesignTool
but i can't open usercontrol in visual studio for designing purpose
I am designing a WPF user control which contains other user controls (imagine a WidgetContainer, containing different Widgets) - using M-V-VM architecture.
During development, I have WidgetContainerView in a window, window (View) spawns a WidgetContainerViewModel as its resource, and in a parameterless constructor of WidgetContainerViewModel, I fill its exposed collection with some sample widgets (WidgetViewModels).
WidgetContainer control inherits the DataContext from window, and inside, there is a ListView, that binds Widgets to WidgetView control (which is inside ListView.ItemTemplate).
Now this works OK in my WindowView, as I see my sample widgets, but once I edit the WidgetContainerView or WidgetView, there is no content - at design time, controls are standalone, and they don't inherit any DataContext, so I don't see a content, and have troubles designing them (a ListView is empty, Widget's fields as well...).
I tried adding a sample widget to the WidgetView:
public partial class WidgetView : UserControl
{
public WidgetView()
{
InitializeComponent();
if (LicenseManager.UsageMode == LicenseUsageMode.Designtime)
{
//btw, MessageBox.Show(...) here sometimes crashes my Visual Studio (2008), but I have seen the message - this code gets executed at design time, but with some lag - I saw the message on reload of designer, but at that time, I have already commented it - wtf?
this.DataContext = new WidgetViewModel(); //creates sample widget
}
}
}
but that didn't work - I still don't see anything in designer.
I also wanted to create a WidgetViewModel as a resource in WidgetView, like this:
<UserControl x:Class="MVVMTestWidgetsControl.View.WidgetView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
DataContext="WidgetViewModel" //this doesn't work!
Height="Auto" Width="Auto">
<UserControl.Resources>
<ResourceDictionary>
<ViewModel:WidgetViewModel x:Key="WidgetViewModel" />
</ResourceDictionary>
</UserControl.Resources>
<TextBlock Text="{Binding Path=Title}"></TextBlock>
</UserControl>
but I don't know how to assign a WidgetViewModel as a DataContext of a whole widget - I can't add DataContext attribute to UserControl, because WidgetViewModel is defined later in the code. Any ideas how to do this? I could use a sample data this way, and just override it in code so that it has the right content at runtime...
What are your best practices when developing user controls? Thank you, designing empty control is no fun :)).
In your second snippet, you should be able to refer to your DataContext as a DynamicResource:
DataContext="{DynamicResource WidgetViewModel}"
But most custom user controls have some sort of top level layout container, and you can set the DataContext on that container as a StaticResource.
In your case, however, you may want to consider dropping the VM portion of your code altogether since you're writing a custom UserControl. You should ask yourself what benefits are you gaining from a completely self-contained ViewModel with no real backing Model designed for just one View (i.e. the custom UserControl). Perhaps you could just define some DependencyProperties and use those?
I came up with several solutions: Add DC as resource (it will get automatically instantiated with parameterless constructor), and do the following in View's codebehind:
public PanelView()
{
InitializeComponent();
if (!DesignerProperties.GetIsInDesignMode(new DependencyObject())) //DeleteAtRelease:
{
//we are in runtime, reset DC to have it inherited
this.DataContextHolder.DataContext = DependencyProperty.UnsetValue;
}
}
Better way would be to only assign DC if we are at designtime, but VS didn't like it - it worked only sometimes, and quite nondeterministically, and once it even crashed.
Other check for design time is:
if (LicenseManager.UsageMode == LicenseUsageMode.Designtime)
{
this.DataContext = new WidgetViewModel();
}