I can't figure out why the binding changes in my large project wont work. I have simplified it down to a sample project that still doesn't work. I would like to continue to set the datacontext the way I currently am if possible because that is how the other project does it. With the following code the text in SomeText is not showing up in the textbox. How do I fix this?
Code Behind:
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
DataContext = new ViewModel();
}
}
Data Class:
public class ViewModel
{
public string SomeText = "This is some text.";
}
Main User Control:
<UserControl xmlns:ig="http://schemas.infragistics.com/xaml" x:Class="XamGridVisibilityBindingTest.MainPage"
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:XamGridVisibilityBindingTest="clr-namespace:XamGridVisibilityBindingTest" mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">
<Grid x:Name="LayoutRoot" Background="White">
<TextBox Text="{Binding SomeText}" BorderBrush="#FFE80F0F" Width="100" Height="50"> </TextBox>
</Grid>
</UserControl>
Edit: I am only trying to do one-way binding.
You need to use a property, and make your VM inherit from INotifyPropertyChanged and raise the PropertyChanged event whenever SomeText changes:
public class ViewModel : INotifyPropertyChanged
{
private string someText;
public event PropertyChangedEventHandler PropertyChanged;
public string SomeText
{
get { return someText; }
set
{
someText = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("SomeText"));
}
}
}
public ViewModel()
{
SomeText = "This is some text.";
}
}
I figured it out, you can only bind to Properties!
public class ViewModel
{
public string SomeText { get; set; }
public ViewModel()
{
SomeText = "This is some text.";
}
}
Related
I'm new to Prism and I'm trying to update a text in MainWindow.xaml another view in region.
MainWindowViewModel
private string _message = "Prism";
public string Message
{
get { return _message; }
set { SetProperty(ref _message, value);}
}
MainWindow.xaml
<Window x:Class="XXXX.Views.MainWindow"
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"
Title="{Binding Title}">
<Grid>
<StackPanel>
<TextBlock Text="{Binding Message, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" FontSize="48"></TextBlock>
<ContentControl prism:RegionManager.RegionName="ViewARegion" />
</StackPanel>
</Grid>
ViewAViewModel
public ICommand ClickCommand
{
get;
private set;
}
public ViewAViewModel()
{
ClickCommand = new DelegateCommand(ClickedMethod);
}
private void ClickedMethod()
{
MainWindowViewModel mainWindowViewModel = new MainWindowViewModel();
mainWindowViewModel.Message = "Prism View A";
}
ViewA.xaml
<UserControl x:Class="XXXX.Views.ViewA"
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:XXXX.Views"
xmlns:prism="http://prismlibrary.com/"
prism:ViewModelLocator.AutoWireViewModel="True"
mc:Ignorable="d">
<Grid>
<StackPanel>
<Button Content="Click"
Command="{Binding ClickCommand}">
</Button>
</StackPanel>
</Grid>
Now when I click the button it's working correctly I mean it's setting the Message property in MainWindowViewModel but it's not udating the View in MainWindow.xaml.
What should I do to get this working as I'm expecting to update the view on button click?
MainWindowViewModel mainWindowViewModel = new MainWindowViewModel();
mainWindowViewModel.Message = "Prism View A";
This creates a new instance of MainWindowViewModel that has nothing to do with the instance that's bound to your MainWindow. You can change properties on this new instance all day long, the real view model will not care.
You have to implement some view model to view model communication mechanism, e.g. use IEventAggregator or a shared service, so that the information ("click happened" or "message changed" or whatever) can be passed from ViewA to the MainWindow.
You could use the event aggregator to send an event from ViewAViewModel to MainWindowViewModel:
public class ViewAViewModel
{
private readonly IEventAggregator _eventAggregator;
public ViewAViewModel(IEventAggregator eventAggregator)
{
_eventAggregator = eventAggregator;
ClickCommand = new DelegateCommand(ClickedMethod);
}
public ICommand ClickCommand
{
get;
private set;
}
private void ClickedMethod()
{
_eventAggregator.GetEvent<PubSubEvent<string>>().Publish("Prism View A");
}
}
public class MainWindowViewModel : BindableBase
{
public MainWindowViewModel(IEventAggregator eventAggregator)
{
eventAggregator.GetEvent<MessageSentEvent>().Subscribe(MessageReceived);
}
private void MessageReceived(string message)
{
Message = message;
}
private string _message = "Prism";
public string Message
{
get { return _message; }
set { SetProperty(ref _message, value); }
}
}
There is a complete example available on GitHub: https://github.com/PrismLibrary/Prism-Samples-Wpf/tree/master/14-UsingEventAggregator
New to WPF.
I am trying to bind my Model to my UI. So, when the Property is changed during my User actions I want the field to update whereever it occurs on my UI.
This is my Model:
namespace WpfApplication1
{
public class model2
{
private static string myField2;
public static string MyField2
{
get { return myField2; }
set { myField2 = value; }
}
}
}
My Markup:
<Window x:Class="WpfApplication1.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:WpfApplication1"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<local:model2 x:Key="mymodel"/>
</Window.Resources>
<Grid>
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding Source={StaticResource ResourceKey=mymodel}, Path=MyField2}"></TextBlock>
<Button Content="static test!" Click="Button_Click_1" />
</StackPanel>
</Grid>
</Window>
My code behind:
using System.Windows;
namespace WpfApplication1
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
model2.MyField2 = "static!";
}
}
}
The field on the UI does not change?
You need to notify changes to the UI so it can update with new values.
In your case you want to notify static properties of changes so you would need a static event. The problem is the INotifyPropertyChanged interface needs a member event so you won't be able to go that way.
You best shot is to implement the Singleton pattern:
namespace WpfApplication1
{
public class model2 : INotifyPropertyChanged
{
//private ctor so you need to use the Instance prop
private model2() {}
private string myField2;
public string MyField2
{
get { return myField2; }
set {
myField2 = value;
OnPropertyChanged("MyField2");
}
}
private static model2 _instance;
public static model2 Instance {
get {return _instance ?? (_instance = new model2();)}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName) {
var handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
And then make your property a member property and bind like this:
<Window x:Class="WpfApplication1.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:WpfApplication1"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<local:model2 x:Key="mymodel"/>
</Window.Resources>
<Grid>
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding Source={x:Static local:model2.Instance}, Path=MyField2}"/>
<Button Content="static test!" Click="Button_Click_1" />
</StackPanel>
</Grid>
</Window>
Code behind:
using System.Windows;
namespace WpfApplication1
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
model2.Instance.MyField2 = "static!";
}
}
}
Use the Static extension to bind the TextBlocks Text Property:
<TextBlock Text="{Binding Source={Static MyModel.MyField2}, Mode=TwoWay">
But still the Property must raise the PropertyChanged event. My understanding why you use the static field is to be able to set the value from somewhere else. Have you thougt about using messages instead? Checkout the MVVM Light toolkit and the messenger. This would decouple the two components
I think that static properties are not what you want to use, from comments I can deduce that you are using only to make your program work. Below is the full working code.
App.xaml
Remove the code StartupUri="MainWindow.xaml instead we will instantiate MainWindow in code-behind to provide DataContext.
App.xaml.cs
Here we are assigning object of Model2 as Window.DataContext and then showing the window.
public partial class App : Application
{
public App()
{
Model2 model = new Model2();
MainWindow window = new MainWindow();
window.DataContext = model;
window.Show();
}
}
MainWindow.xaml.cs
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
//We get hold of `DataContext` object
var model = this.DataContext as Model2;
model.MyField2 = "Hello World";
}
}
Model:
public class Model2 : INotifyPropertyChanged
{
private string _myField2;
public string MyField2
{
get { return _myField2; }
set
{
_myField2 = value;
OnPropertyChanged("MyField2");
}
}
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
MainWindow.xaml
<Window x:Class="WpfApplication2.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>
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding MyField2}"></TextBlock>
<Button Content="static test!" Click="ButtonBase_OnClick" />
</StackPanel>
</Grid>
</Window>
And I checked, it works !
I'm trying to create a user control with dependency properties to bind to. Internally I have a ComboBox that is bound to these same properties, but the binding only works one way. The ComboBox fills from the ItemsSource, but SelectedItem doesn't get updated back to the viewmodel I'm binding to.
A simplified example:
This is the view model to bind with the user control:
public class PeopleViewModel : INotifyPropertyChanged
{
public PeopleViewModel()
{
People = new List<string>( new [] {"John", "Alfred","Dave"});
SelectedPerson = People.FirstOrDefault();
}
public event PropertyChangedEventHandler PropertyChanged;
private IEnumerable<string> _people;
public IEnumerable<string> People
{
get { return _people; }
set
{
_people = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("People"));
}
}
}
private string _selectedPerson;
public string SelectedPerson
{
get { return _selectedPerson; }
set
{
_selectedPerson = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("SelectedPerson"));
}
}
}
}
This is the User control:
<UserControl x:Class="PeopleControlTest.PeopleControl"
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="56" d:DesignWidth="637">
<StackPanel >
<ComboBox Margin="11"
ItemsSource="{Binding BoundPeople, RelativeSource={RelativeSource AncestorType=UserControl}}"
SelectedItem="{Binding BoundSelectedPerson, RelativeSource={RelativeSource AncestorType=UserControl}}"/>
</StackPanel>
with code behind
public partial class PeopleControl : UserControl
{
public PeopleControl()
{
InitializeComponent();
}
public static readonly DependencyProperty BoundPeopleProperty =
DependencyProperty.Register("BoundPeople", typeof(IEnumerable<string>), typeof(PeopleControl), new UIPropertyMetadata(null));
public static readonly DependencyProperty BoundSelectedPersonProperty =
DependencyProperty.Register("BoundSelectedPerson", typeof(string), typeof(PeopleControl), new UIPropertyMetadata(""));
public IEnumerable<string> BoundPeople
{
get { return (IEnumerable<string>)GetValue(BoundPeopleProperty); }
set { SetValue(BoundPeopleProperty, value); }
}
public string BoundSelectedPerson
{
get { return (string)GetValue(BoundSelectedPersonProperty); }
set { SetValue(BoundSelectedPersonProperty, value); }
}
}
And this is how I bind the user control in the main window (with the windows data context set to an instance of the viewmodel)
<Window x:Class="PeopleControlTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:controls="clr-namespace:PeopleControlTest"
Title="MainWindow" Height="350" Width="525">
<Grid>
<controls:PeopleControl
BoundPeople="{Binding People}"
BoundSelectedPerson="{Binding SelectedPerson}"/>
</Grid>
</Window>
The combobox in the user control fills with the names, but when I select a different name this doesn't get updated back to the view model. Any idea what I'm missing here?
Thanks!
Some properties bind two-way by default (Including SelectedItem) but your BoundSelectedPerson does not. You can set the Mode of the binding:
<controls:PeopleControl
BoundPeople="{Binding People}"
BoundSelectedPerson="{Binding SelectedPerson, Mode=TwoWay}"/>
Or you can make it TwoWay by default by setting a flag on the DependencyProperty:
public static readonly DependencyProperty BoundSelectedPersonProperty =
DependencyProperty.Register("BoundSelectedPerson", typeof(string), typeof(PeopleControl), new FrameworkPropertyMetadata("",FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
Did this:
public class myClass : INotifyPropertyChanged
{
public bool? myFlag = false;
public bool? MyFlag
{
get { return myFlag; }
set
{
myFlag = value;
OnPropertyChanged("MyFlag");
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string name)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
Declared a test variable myClass in the Window1 class:
public partial class Window1 : Window
{
myClass test;
public Window1()
{
InitializeComponent();
test = new myClass();
}
}
Here's an example XAML file:
<Window x:Class="WpfApplication5.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300" IsEnabled="{Binding ElementName=test, Path=MyFlag}">
<Grid>
<Button>You shouldn't be clicking me</Button>
</Grid>
</Window>
The window isn't disabled, and the debugger is showing me that message.
What am I missing?
The ElementName property of the Binding is meant to target other elements in xaml, not properties/fields of the object. The common way to do what you're trying to accomplish is to assign an instance of myClass to the Window's DataContext property:
public partial class Window1 : Window
{
//myClass test;
public Window1()
{
InitializeComponent();
this.DataContext = new myClass(); //test = new myClass();
}
}
And then your binding will look like this: IsEnabled="{Binding Path=MyFlag}".
If you actually wanted to bind to a property on the Window itself, you would use a binding like this:
IsEnabled="{Binding RelativeSource={RelativeSource Self}, Path=test.MyFlag}"
I have a custom base user control in silverlight.
<UserControl x:Class="Problemo.MyBaseControl"
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"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">
<Grid x:Name="LayoutRoot" Background="White">
<Border Name="HeaderControl" Background="Red" />
</Grid>
</UserControl>
With the following code behind
public partial class MyBaseControl : UserControl
{
public UIElement Header { get; set; }
public MyBaseControl()
{
InitializeComponent();
Loaded += MyBaseControl_Loaded;
}
void MyBaseControl_Loaded(object sender, RoutedEventArgs e)
{
HeaderControl.Child = Header;
}
}
I have a derived control.
<me:MyBaseControl x:Class="Problemo.MyControl"
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"
mc:Ignorable="d"
xmlns:me="clr-namespace:Problemo"
d:DesignHeight="300" d:DesignWidth="400">
<me:MyBaseControl.Header>
<TextBlock Name="header" Text="{Binding Text}" />
</me:MyBaseControl.Header>
</me:MyBaseControl>
With the following code behind.
public partial class MyControl : MyBaseControl
{
public string Text
{
get; set;
}
public MyControl(string text)
{
InitializeComponent();
Text = text;
}
}
I'm trying to set the text value of the header textblock in the derived control.
It would be nice to be able to set both ways, i.e. with databinding or in the derived control code behind, but neither work. With the data binding, it doesn't work. If I try in the code behind I get a null reference to 'header'. This is silverlight 4 (not sure if that makes a difference)
Any suggestions on how to do with with both databinding and in code ?
Cheers
First of all I'll show you how to adjust your Derived control to handle this. You need to do two things, first you need to implement INotifyPropertyChanged and secondly you to add the binding to the user control.
MyControl Xaml:-
<me:MyBaseControl.Header>
<TextBlock Name="headerItem" />
</me:MyBaseControl.Header>
MyControl code:-
public partial class MyControl : MyBaseControl, INotifyPropertyChanged
{
public MyControl ()
{
InitializeComponent();
headerItem.SetBinding(TextBlock.TextProperty, new Binding("Text") { Source = this });
}
string _text;
public string Text
{
get { return _text; }
set { _text = value; NotifyPropertyChanged("Text"); }
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
void NotifyPropertyChanged(string name)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
#endregion
}
This should get you working. However, as soon as you feel you need to inherit a UserControl based class you should take a step back and ask whether the base and derived items ought to be templated controls instead. If I get time I'll try to add a version of your code in terms of templated controls.