I'm just starting out with WPF having used WinForms for some time and seem to have fallen at the first hurdle.
I have my main XAMLdefined as
<Window x:Class="FHIRCDALoader.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:FHIRCDALoader.xaml"
Title="FHIR CDA Loader" Height="350" Width="525"
Icon="Icons/color_swatch.png">
<Window.CommandBindings>
<CommandBinding Command="ApplicationCommands.New"
Executed="NewDocument" />
</Window.CommandBindings>
<DockPanel>
<local:menubar DockPanel.Dock="Top"/>
<local:toolbar DockPanel.Dock="Top"/>
<local:statusbar DockPanel.Dock="Bottom" />
<RichTextBox x:Name="Body"/>
</DockPanel>
</Window>
Note the use of the user controls, one of which is the "statusbar"
<UserControl x:Class="FHIRCDALoader.xaml.statusbar"
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">
<StatusBar >
<StatusBarItem>
<TextBlock x:Name="bbstatusbar" />
</StatusBarItem>
</StatusBar>
</UserControl>
So in MainWindow.xaml.cs I see I can reference RichTextBox named body from the main XAML file. I can't however reference the TextBlock in the UserControl which is named "bbstatusbar".
How do I set the value of the TextBlock from MainWindow.xaml.cs?
In agreement with Vlad and HighCore's comments: you don't set the TextBlock from MainWindow.xaml.cs. You bind it to a view-model. A binding simply looks like this:
<TextBlock Text="{Binding StatusText}" />
The above says: bind the Text property to a property in the current data-context called "StatusText". Next, create a view model:
public class ViewModel : INotifyPropertyChanged
{
public string StatusText
{
get { return _statusText; }
set
{
_statusText = value;
RaisePropertyChanged("StatusText");
}
}
// TODO implement INotifyPropertyChanged
}
Finally, set the DataContext of your MainPage to the view model. You can do this in a variety of ways, but let's say here for simplicity, do it in the constructor:
public MainWindow()
{
InitializeComponent();
DataContext = new ViewModel { StatusText = "hello world" };
}
Now, the idea is to put your model-related logic into ViewModel. So, you shouldn't need to access the UI elements -- instead, update the view-model properties that the UI elements are bound to.
Related
I have the following very simple WPF application:
A User control:
XAML:
<UserControl x:Class="WPFUserControlTest.TestControl"
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"
xmlns:local="clr-namespace:WPFUserControlTest"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800"
x:Name="root">
<Grid>
<TextBlock Text="{Binding ElementName=root, Path=InputString}"/>
</Grid>
Code Behind:
namespace WPFUserControlTest
{
public partial class TestControl : UserControl
{
public TestControl()
{
InitializeComponent();
}
public string InputString
{
get { return (string)GetValue(InputStringProperty); }
set { SetValue(InputStringProperty, value); }
}
public static readonly DependencyProperty InputStringProperty =
DependencyProperty.Register("InputString", typeof(string), typeof(TestControl), new PropertyMetadata(""));
}
}
My Main Window:
<Window x:Class="WPFUserControlTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WPFUserControlTest"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<StackPanel>
<local:TestControl x:Name="Mercedes" InputString="Mercedes"/>
<local:TestControl InputString="Volvo"/>
</StackPanel>
</Grid>
</Window>
What i wonder is how it can be that the binding inside the user control that uses ElementName seems to work even though the main window changes the name of the control.
Is this binding done internally in the control somehow at compile time?
When i look at this is in the Live Visual Tree I see that one of my control instances has name "root" and one is named "mercedes". Still both of them works as expected...
You should read up on XAML namescopes. The name "Mercedes" is only applicable in the namescope of the window and "root" in the namescope of the UserControl.
The window cannot refer to the UserControl as "root" because it doesn't belong to the same namescope.
I have a ViewModel that has a property which is a ReadOnlyObservableCollection. Defined something like this:
public class MyViewModel
{
private ObservableCollection<string> myProtectedCollection;
public ReadOnlyObservableCollection<string> MyCollectionProperty { get; }
public MyViewModel()
{
this.myProtectedCollection = new ObservableCollection<string>();
this.MyCollectionProperty = new ReadOnlyObservableCollection<string>(this.myProtectedCollection);
this.myProtectedCollection.Add("String1");
this.myProtectedCollection.Add("String2");
this.myProtectedCollection.Add("String3");
}
}
I have then created a xaml file called TestData.xaml and set the build action to DesignData. In that I have this:
<local:MyViewModel
xmlns:local="clr-namespace:ScrapWpfApplication1"
xmlns:system="clr-namespace:System;assembly=mscorlib">
<local:MyViewModel.MyCollectionProperty>
<system:String>String 1</system:String>
<system:String>String 2</system:String>
</local:MyViewModel.MyCollectionProperty>
</local:MyViewModel>
Finally I have a MainWindow.xaml with the following:
<Window x:Class="ScrapWpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:ScrapWpfApplication1"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525"
d:DataContext="{d:DesignData Source=SampleData.xaml}">
<ListBox ItemsSource="{Binding MyCollectionProperty}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Window>
The problem is that this is not showing my sample data in the Visual Studio designer. If I change the collection in my view model to be a ObservableCollection instead of a ReadOnlyObservableCollection then it works as expcted.
I guess that this is because the design time data system is creating a dummy ReadOnlyCollection but XAML is unable to populate it because it is readonly.
Is there any way to get the design type data system to work without making my view model's collection property writeable?
Is there any way to get the design type data system to work without making my view model's collection property writeable?
Yes, you could create another view model class, to be used for design purposes only, with an ObservableCollection<T> property, and set the design time DataContext of the view to an instance of this one:
d:DataContext="{d:DesignInstance Type=local:DesignTimeViewModel, IsDesignTimeCreatable=True}
I've not seen a perfect answer to this. But this is what I have finally done.
Instead of trying to get the design data system to mock the readonly collection. I've created a new set of sample data just for the collection and made the MainWindow.xaml look at that instead.
So my TestData.xaml file changes to just this. In reality it has more in it but this is just a sample for this question so it looks fairly empty.
<local:MyViewModel
xmlns:local="clr-namespace:ScrapWpfApplication1"
xmlns:system="clr-namespace:System;assembly=mscorlib">
</local:MyViewModel>
Secondly I created a second test data file called TestDataArray.xaml with an array in it. Being sure to set the build action to DesignData.
<x:Array Type="system:String"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:ScrapWpfApplication1"
xmlns:system="clr-namespace:System;assembly=mscorlib">
<system:String>String 1</system:String>
<system:String>String 2</system:String>
</x:Array>
Finally I changed my MainWindow.xaml file to this. Note the change to the binding on
<Window x:Class="ScrapWpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:ScrapWpfApplication1"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525"
d:DataContext="{d:DesignData Source=SampleData.xaml}">
<ListBox ItemsSource="{Binding}" DataContext="{Binding MyCollectionProperty}" d:DataContext="{d:DesignData Source=SampleDataArray.xaml}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Window>
This works for my particular scenario, but it would fall down if the sample data was being bound to a control and the ReadOnlyCollection was being read by something inside that control.
I am using Prism 7.1 navigation framework (WPF) to get a dialog window to pop up using the configuration below. This is successful. However, I want this popup to have tabs that I can navigate back and forth among. When I click the button on the popup box in an attempt to display ViewA inside of it, nothing happens. By setting a breakpoint, I see that the navigation path is hit, and is displaying the correct view name. Refer to PopUpWindow.cs. However when it goes to resolve the view, the view does not display. Even worse, no error is thrown! I am confused as to why this is occurring.
Assuming my namespaces are correct, what am I doing wrong?
PrismApplication.cs
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
containerRegistry.RegisterForNavigation<ViewA>();
}
//Have tried register type, register type for navigation, etc etc.
MainWindowViewModel.xaml
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:prism="http://prismlibrary.com/"
prism:ViewModelLocator.AutoWireViewModel="True"
Height="350" Width="525">
<i:Interaction.Triggers>
<prism:InteractionRequestTrigger SourceObject="{Binding NotificationRequest}">
<prism:PopupWindowAction IsModal="True" CenterOverAssociatedObject="True" />
</prism:InteractionRequestTrigger>
</i:Interaction.Triggers>
<StackPanel>
<Button Margin="5" Content="Raise Default Notification" Command="{Binding NotificationCommand}" />
</StackPanel>
MainWindowViewModel.cs
public MainWindowViewModel
{
public InteractionRequest<INotification> NotificationRequest { get; set; }
public DelegateCommand NotificationCommand { get; set; }
public MainWindowViewModel()
{
NotificationRequest = new InteractionRequest<INotification>();
NotificationCommand = new DelegateCommand(RaiseNotification);
}
void RaiseNotification()
{
NotificationRequest.Raise(new PopupWindow());
}
}
PopUpWindow.xaml
<UserControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:prism="http://prismlibrary.com/"
prism:ViewModelLocator.AutoWireViewModel="True"
Height="350" Width="525">
<DockPanel LastChildFill="True">
<StackPanel Orientation="Horizontal" DockPanel.Dock="Top" Margin="5" >
<Button Command="{Binding NavigateCommand}" CommandParameter="ViewA" Margin="5">Navigate to View A</Button>
</StackPanel>
<ContentControl prism:RegionManager.RegionName="ContentRegion" Margin="5" />
</DockPanel>
</UserControl>
PopUpWindow.cs
public class PopupWindowViewModel
{
private readonly IRegionManager _regionManager;
public DelegateCommand<string> NavigateCommand { get; private set; }
public PopupWindowViewModel(IRegionManager regionManager)
{
_regionManager = regionManager;
NavigateCommand = new DelegateCommand<string>(Navigate);
}
private void Navigate(string navigatePath)
{
if (navigatePath != null)
_regionManager.RequestNavigate("ContentRegion", navigatePath);
//During debugging, this correctly shows navigatePath as "ViewA"
}
}
ViewA.xaml
<UserControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:prism="http://prismlibrary.com/"
prism:ViewModelLocator.AutoWireViewModel="True">
<Grid>
<TextBlock Text="ViewA" FontSize="48" HorizontalAlignment="Center" VerticalAlignment="Center" />
</Grid>
</UserControl>
Maybe it's just not finding your view.
Isn't the second parameter supposed to be a url rather than a string?
From here:
https://prismlibrary.github.io/docs/wpf/Navigation.html
IRegionManager regionManager = ...;
regionManager.RequestNavigate("MainRegion",
new Uri("InboxView", UriKind.Relative));
Check where your view is and what the path should be.
I think you could prove that using something like:
var testinstance = System.Windows.Application.LoadComponent(testUrl);
https://learn.microsoft.com/en-us/dotnet/api/system.windows.application.loadcomponent?view=netframework-4.7.2
And if you're using MEF I think you also need to mark the View with the Export attribute.
Hopefully your problem is just you forgot about a folder or some such.
If not then it could be related to regionmanager not getting a reference to your region.
Regions that aren't in the visual tree are ignored by the region manager. You define ContentRegion within the PopUpWindow (which is lazily created), so it is not there and the navigation request for the unknown region is just ignored.
As detailled here and there, in this case, you have to add the region manually in the constructor of the view containing it:
RegionManager.SetRegionName( theNameOfTheContentControlInsideThePopup, WellKnownRegionNames.DataFeedRegion );
RegionManager.SetRegionManager( theNameOfTheContentControlInsideThePopup, theRegionManagerInstanceFromUnity );
with a region manager from the ServiceLocator:
ServiceLocator.Current.GetInstance<IRegionManager>()
The InteractionRequest pattern is a bit quirky. You need to make sure that all views that should react on the request have the necessary InteractionRequestTrigger in the visual tree. Thus, the immediate fix to your problem is to copy your XAML from MainWindowView.xaml to ViewA.xaml:
<UserControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:prism="http://prismlibrary.com/"
prism:ViewModelLocator.AutoWireViewModel="True"
Height="350" Width="525">
<i:Interaction.Triggers>
<prism:InteractionRequestTrigger SourceObject="{Binding NotificationRequest}">
<prism:PopupWindowAction IsModal="True" CenterOverAssociatedObject="True" />
</prism:InteractionRequestTrigger>
</i:Interaction.Triggers>
<!-- ... -->
</UserControl>
Then make sure to add the NotificationRequest in the viewmodel for ViewA. Please note that you may still encounter scenarios where the interaction request doesn't work. E.g. when adding triggers inside a data template. Though, as long as you put them on the UserControl level you should be fine.
One possible improvement to this (flawed) design is to create a behavior where you programmatically add these interaction triggers.
I'm not able to display a property value on the usercontrol.
I set up the datacontext in this way:
public MainController cm;
public static MainWindow AppWindow;
public partial class MainWindow
{
public MainWindow()
{
InitializeComponent();
cm = new MainController();
DataContext = cm;
AppWindow = this;
}
}
inside MainController I've all the controller with all the properties like this:
public class MainController: MainControllerVM
{
private ClubController _clubController = new ClubController();
public ClubController ClubController
{
get { return _clubController ; }
}
}
Now I've splitted my user interface in different controls to have more xaml organization. I need to access to the main datacontext that's cm from all user controls, I tried in this way:
public partial class Club : UserControl
{
public Club ()
{
InitializeComponent();
DataContext = MainWindow.AppWindow.cm;
}
but I get:
NullReferenceException
on AppWindow. My main problem's that I can't get to display the value of the property on a label available on the user control:
<Label Content="{Binding ClubController.Club.Name}" />
this binding working in the main window but not working on usercontrol, why??
Suppose you have a window like this:
<Window x:Class="Example.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Example"
Title="MainWindow" Height="350" Width="525">
<UniformGrid Rows="2" Columns="2">
<local:MyUserControlA/>
<local:MyUserControlB/>
<local:MyUserControlC/>
<local:MyUserControlD/>
</UniformGrid>
</Window>
And you set the DataContext in the constructor:
public MainWindow()
{
InitializeComponent();
DataContext = this;
}
Now remember that the DataContext is an inheritable dependency property, i.e. it flows down. (In general, dependency properties are not inheritable by default, unless you explicitly state it)
So, you set the DataContext once on the root of the logical tree (the window) and all of its children will "see" it. (the UniformGrid and the custom controls in our case)
Yes, that means you can directly bind to the view model in your user control's XAML:
<UserControl x:Class="Example.MyUserControlA"
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>
<TextBlock Text="{Binding PropertyFromMainViewModel}"/>
</Grid>
</UserControl>
Now, this approach works well, until your control gets so complicated that it needs to have its own ViewModel and DataContext reespectively.
Usually this happens when the control is not a passive, but maintains a state (validates input, button state, etc.)
1.Declare all properties that you want to bind to the main view model as dependency properties and pay attention to the default value you specify.
2.Locate the main panel of your UserControl and name it, for example "LayoutRoot":
<UserControl x:Class="Example.MyUserControlA"
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 x:Name="LayoutRoot">
<TextBlock Text="{Binding MyDependencyProperty}"/>
</Grid>
</UserControl>
3.Now, you set the DataContext on the LayoutRoot
public MyUserControlA()
{
InitializeComponent();
LayoutRoot.DataContext = new MyUserControlViewModel();
}
4.You bind to the main view model in this way
<Window x:Class="Example.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Example"
Title="MainWindow" Height="350" Width="525">
<UniformGrid Rows="2" Columns="2">
<local:MyUserControlA MyDependencyProperty="{Binding MainViewModelProperty}"/>
<local:MyUserControlB/>
<local:MyUserControlC/>
<local:MyUserControlD/>
</UniformGrid>
</Window>
The other way around is to bind using RelativeSource, but this would break the encapsulation and reusability of your UserControl.
WPF has a steep learning curve, I hope my tips were helpful...
I defined an object which contains properties in code-behind and, want to set the object to datacontext in xaml.
namespace WpfApplication4
{
public partial class MainWindow : Window
{
public EquipInfo equip1;
public MainWindow()
{
InitializeComponent();
equip1 = new EquipInfo();
// setting here works fine but i want to do in xaml
//textBox1.DataContext = equip1;
}
}
}
here's xaml code..
<Window x:Class="WpfApplication4.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TextBox Text="{Binding Path=PIN}" Height="23"
HorizontalAlignment="Left" Margin="172,208,0,0"
Name="textBox1" VerticalAlignment="Top" Width="120" />
</Grid>
</Window>
You can set the DataContext via XAML to a public property. blindmeis has given a good example on how to do this.
What you did in your Post was not setting the DataContext, but binding the Text Property of your Control to a Property of the window. This only works if a DataContext is set. Another way to do that, if you don't want to do MVVM (which I'd recommend, though), is referencing specific Elements in your Binding:
1.) Alter member to AutoProperty or similar
public EquipInfo equip1 {get;set;}
2.) Give your window a name
<Window x:Class="WpfApplication4.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Name="myWin"
Title="MainWindow" Height="350" Width="525">
2.) Access Window Properties by instance name
<TextBox Text="{Binding ElementName=myWin, Path=equip1.PIN}"/>
On a side note, it would really be better to use a MVVM instead.
when you create your equipinfo class in codebehind why not setting the datacontext there?
nevertheless you can create a datacontext in xaml (you did not need the codebehind stuff then)
<TextBox Text="{Binding Path=PIN}">
<TextBox.DataContext>
<local:equip1/>
</TextBox.DataContext>
</TextBox>
but please look at the MVVM pattern
When you create your equipinfo class in codebehind why not setting the datacontext there?
The whole point of MVVM is to seperate UI from code behind using a viewmodel proxy. If you are going to reference the ui element to set its datacontext you might just as well reference it to set its value and forget about mvvm.