WP7/XAML: data binding to a property in the code-behind file - xaml

I'm rather new to XAML and Silverlight. I have a XAML page and a code behind class for it. In the class, I have a protected read-only property. Can I bind a control to that property? Trying to specify the root element of the XAML as the DataContext (by name, as an ElementName) causes a designer error "Value does not fall within the expected range."
EDIT: I'd like to do in the designer-fiendly way. I understand I can do everything (including control population) from code; that's not the point. Can I have the designer recognize and display the properties of my code-behind class? Not one ones from the base (PhoneApplicationPage) but the ones that I define?

Your code behind should be the datacontext.
For example on a main page code behind:
public MainPage()
{
InitializeComponent();
DataContext = this;
}
You should be able to bind to the protected property but only one way ie from the property to the xaml. As it is read-only you will not be able to get the value if it is changed on the page by the user.

Related

Struggling With MVVM

I have a class named osmAppBarButton that inherits from AppBarButton (UWP) to which I have added a dependency property named ButtonState. (Enum Normal, Dim, Bright, Flash)
I have a Style used on all my osmAppBarButtons, that uses a DataTriggerBehavior to check the ButtonState and select the appropriate VisualState.
I was rather please with myself, as DPs and the VisualStateManager are all new to me. Then I hit a problem..
How can I change an osmAppBarButton's ButtonState from the ViewModel without breaking MVVM ? I thought about having a VM property for the ButtonState of each button in my view, but that would imply that the VM would have some knowledge of the View.
I think that the answer may lie with Attached Behaviours, but I haven't found an example that suits.
Any ideas ?
The way you get values from a viewmodel property to a dependency property is to use a Binding. Certainly not an attached behavior; I'm sure you could find some way to do that with an attached behavior, but just use a Binding.
`The viewmodel must implement INotifyPropertyChanged, and it must be the DataContext for the view where the appbar button lives, and you must not be shooting yourself in the foot by binding DataContext to something random in some parent of the appbar button.
Give the viewmodel a public property that raises PropertyChanged when its value changes. Bind to that property.
An enum like ButtonState with Normal, Dim, Bright, Flash values isn't the kind of thing a viewmodel should be aware of in a "proper" MVVM implementation. This isn't actually a silly point, either. I would suggest having the viewmodel expose its state through properties that express the viewmodel's state in its own terms (I could give you an example, if I knew what you were doing here). Maybe the viewmodel has a State that can be Normal, Busy, Error, Waiting -- those might map onto various ButtonState values. "Error" is a state of the viewmodel. "Flash" is one of many ways a view might choose to communicate a given viewmodel state to the user.
If the viewmodel expresses the relevant state using one or more properties with types other than ButtonState, you'd write a converter -- maybe a multiconverter -- to translate all that into a ButtonState value.
But it won't be the end of the world if your learning program uses ButtonState in a viewmodel, and that'll be simpler. So bind it to this:
private ButtonState _fooBarButtonState = ButtonState.ItsComplicated;
public ButtonState FooBarButtonState {
get { return _fooBarButtonState; }
set {
if (value != _fooBarButtonState) {
_fooBarButtonState = value;
OnPropertyChanged(nameof(FooBarButtonState));
}
}
}
XAML:
<local:osmAppBarButton
ButtonState="{Binding FooBarButtonState}"
/>
But if you'd like to go with my suggestion to use a different state enum in the viewmodel, converters are quite trivial to write. Let me know if you hit a snag, but if you got a dependency property and viewstates working, you'll get it.

Prism MVVM Binding to User Control Dependency Property

I have a Universal app that I'm writing and I want to use Prism and Unity as my MVVM framework. Everything was going great until I got to a view where I have multiple instances of the same user control(a custom Watermark Textbox). For some reason, I haven't been able to find a good solution to my problem. I imagine I'm overlooking something and there is a straightforward answer.
Here's my source code(just the relevant portions). Some background, I had this working before implementing Prism. The Commands attached to the user controls are firing as expected but I can't figure out how to manipulate the control itself):
Any guidance on how to use user controls with Prism or binding to dependency properties with Prism would be great. Thanks.
My View
<!-- I want to be able to set the watermark and also retrieve the text from my ViewModel -->
<uc:WatermarkTextBox Width="250"
x:Name="FullName">
<i:Interaction.Behaviors>
<iCore:EventTriggerBehavior EventName="GotFocus">
<iCore:InvokeCommandAction Command="{Binding EntryFieldFocus}"
CommandParameter="{Binding ElementName=FullName}"/>
</iCore:EventTriggerBehavior>
</i:Interaction.Behaviors>
</uc:WatermarkTextBox>
<!-- This one as well -->
<uc:WatermarkTextBox Width="250"
x:Name="EmailAddress">
<i:Interaction.Behaviors>
<iCore:EventTriggerBehavior EventName="GotFocus">
<iCore:InvokeCommandAction Command="{Binding EntryFieldFocus}"
CommandParameter="{Binding ElementName=EmailAddress}" />
</iCore:EventTriggerBehavior>
</i:Interaction.Behaviors>
</uc:WatermarkTextBox>
Going from your comments/error message ("Failed to assign to property %0") when attempting to bind the property directly, the Property you are trying to bind to isn't a dependency property.
Your WatermarkTextBox only implements a CLR Property, like this:
public class WatermarkTextBox : TextBox {
public object Watermark { get; set; }
}
This can't be used for databinding.
You need to implement it as Dependency Property, like
public class WatermarkTextBox : TextBox {
public object Watermark
{
get { return (object)GetValue(WatermarkProperty); }
set { SetValue(WatermarkProperty, value); }
}
public static readonly DependencyProperty WatermarkProperty =
DependencyProperty.Register("Watermark", typeof(object), typeof(WatermarkTextbox), new PropertyMetadata(null));
}
This will allow to use <uc:WatermarkTextBox Watermark={Binding watermarkText, Mode=TwoWay} for example.
If you can't modify WatermarkTextBox (third-party closed source control), then you'll have to implement an attached behavior and then bind your ViewModel Property to the attached behavior and assign the Watermark property from within it.
If you need TwoWay binding (which is unlikely in case of Watermark property, since it won't be changed from UI), you have to register an event handler (KeyDown in linked answer) to this specific event and pass the new value to the attached property
Except these two ways, there is no way to update a Control's CLR property without violating MVVM.

How do I bind to public methods with xaml and codebehind?

I am setting the DataContext property of my xaml file in codebehind like this.
DataContext = _systemObject;
I want to bind a listview with a public method of the _systemObject that returns a "List" called ListPeople().
How can I do this? do I have to create a property that wraps the ListPeople() method inside _systemObject?
Thank you for reading...

passing view model from page to user control in windows store app

In a Windows Store split app, I want to pass a view model from a page to a user control. The scenario is that I want to reuse some common xaml in multiple pages, using a UserControl like a view.
In the main page:
<common:LayoutAwarePage
...
DataContext="{Binding ViewModel, RelativeSource={RelativeSource Self}}"
... >
<views:MyUserControlView Model="{Binding ViewModel}" />
...
In the user control code:
public sealed partial class MyUserControlView : UserControl
{
public static readonly DependencyProperty ModelProperty =
DependencyProperty.Register("Model", typeof(MenuSource),
typeof(MyUserControlView), null);
...
public ModelType Model
{
get
{
return this.GetValue(ModelProperty) as ModelType ;
}
set
{
this.SetValue(ModelProperty, value);
}
}
The Model setter is never called. How do I hook up the user control to the parent page's view model?
Or, is there a better way to implement shared views for use in pages?
Thanks.
-John
Correct binding would be:
<views:MyUserControlView Model="{Binding}" />
You've already set DataContext for the page above. All bindings are relative to the current DataContext.
The setter still won't be called, though. It is just a wrapper to access the DependencyProperty from code. Binding will call SetValue directly.
Depending on your requirements you might not even need to define your own Model DependencyProperty. Each control automatically inherits DataContext from its parent control. In your example above the user control already has its DataContext set to the same view model as the page.

Getting Unity to Resolve views in XAML

I'm starting out with MVVM, and I'm starting to understand things. I'm currently experimenting with the Cinch framework, though I'm not committed to it as of yet.
I was injecting the ViewModels into the Views using by having a reference to the ViewModel in the codebehind of the view, with the property having a [Dependency] on it, and in the setter it sets the DataContext to the right view, using Unity. Neat trick, I thought.
I'm trying to get my app to work as a single Window, with injected views (As opposed to multiple windows and dealing with opening\closing them)
I changed my views from Windows to UserControls, and added a to the main window.
That worked, but the ViewModel was never injected, presumably because the XAML doesn't use Container.Resolve to create the view, as when I created the view and added it manually in the code-behind using Resolve, the [Dependency] was created.
How can I set up my window, so that if I add a view through XAML, or the view gets changed as a result of a UI action etc, it gets it through Unity, so that it can work its magic?
This problem is normally solved using Regions and the RegionManager. In the main window ViewModel, a set of Regions is created and added to the RegionManager. Then ViewModels can be Resolved and added to the Region.Views collection.
In XAML, the Region is normally injected by having the ItemsSource property of an ItemsControl bound to the region property of the main ViewModel.
So, in the main screen ViewModel you would have something like this:
public class TestScreenViewModel
{
public const string MainRegionKey = "TestScreenViewModel.MainRegion";
public TestScreenViewModel(IUnityContainer container, IRegionManager regionManager)
{
this.MainRegion = new Region();
regionManager.Regions.Add(MainRegionKey, this.MainRegion);
}
public Region MainRegion { get; set; }
}
This would be Resolved normally in your IModule
#region IModule Members
public void Initialize()
{
RegisterViewsAndServices();
var vm = Container.Resolve<SelectorViewModel>();
var mainScreen = Container.Resolve<TestScreenViewModel>();
mainScreen.MainRegion.Add(vm);
var mainView = ContentManager.AddContentView("Test harness", mainScreen);
}
#endregion
And the XAML representation of your template looking something like
<DataTemplate DataType="{x:Type TestModule:TestScreenViewModel}">
<ScrollViewer ScrollViewer.VerticalScrollBarVisibility="Auto">
<StackPanel>
<ItemsControl ItemsSource="{Binding Path=MainRegion.Views}" />
</StackPanel>
</ScrollViewer>
</DataTemplate>
The way to solve your problem is to make your window to have a ViewModel as well, with ViewModels of UserControls exposes as properties on it. Then in your XAML for a window you'd simply use Binding mechanism to bind UserControl's DataContexts to proper properties of your your main ViewModel. And since that main ViewModel is resolved from Unity container it would have all other ViewModel-s injected as needed.