I'm building a Windows Phone 8 app. I have a UserControl whose contents should get updated asynchronously. My model implements INotifyPropertyChanged. When I update a value in my model it propagates to a TextBox control as it should but not to the contents of my UserControl.
What part of the puzzle am I missing or is it just not possible?
Here's my reproduction scenario.
App page:
<phone:PhoneApplicationPage x:Class="BindingTest.MainPage">
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Button Click="Button_Click" Content="Click" HorizontalAlignment="Left" Margin="147,32,0,0" VerticalAlignment="Top"/>
<TextBlock HorizontalAlignment="Left" Margin="69,219,0,0" TextWrapping="Wrap" Text="{Binding Bar}" VerticalAlignment="Top" Height="69" Width="270"/>
<app:MyControl x:Name="Snafu" HorizontalAlignment="Left" Margin="69,319,0,0" Title="{Binding Bar}" VerticalAlignment="Top" Width="289"/>
</Grid>
</phone:PhoneApplicationPage>
This is the code behind with the model class (Foo)
public partial class MainPage : PhoneApplicationPage
{
Foo foo;
// Constructor
public MainPage()
{
InitializeComponent();
foo = new Foo();
ContentPanel.DataContext = foo;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
foo.Bar = "Gnorf";
}
}
public class Foo : INotifyPropertyChanged
{
string bar;
public event PropertyChangedEventHandler PropertyChanged;
void OnPropertyChanged(string name)
{
if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(name));
}
public Foo()
{
Bar = "Welcome";
}
public string Bar
{
get
{
return bar;
}
set
{
bar = value;
OnPropertyChanged("Bar");
}
}
}
The UserControl xaml
<UserControl x:Class="BindingTest.MyControl">
<TextBox x:Name="LayoutRoot" Background="#FF9090C0"/>
</UserControl>
And the code behind for the UserControl
public partial class MyControl : UserControl
{
public MyControl()
{
InitializeComponent();
}
public static readonly DependencyProperty TitleProperty = DependencyProperty.Register("Title", typeof(string), typeof(MyControl), new PropertyMetadata("", OnTitleChanged));
static void OnTitleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
MyControl c = (MyControl)d;
c.Title = e.NewValue as String;
}
public string Title
{
get
{
return (string)GetValue(TitleProperty);
}
set
{
SetValue(TitleProperty, value);
LayoutRoot.Text = value;
}
}
}
When I run the example, the UserControl TextBox will contain welcome. When I click on the button the regular TextBox updates to Gnorf but the UserControl still displays Welcome.
I also discovered that if I only bind to the UserControl the PropertyChanged event handler is null when the call to set_DataContext returns. The DataBinding infrastructure seems to infer that the binding to my UserControl is a one-time binding instead of a regular one-way binding.
Any ideas?
Try This:-
<app:UserControl1 x:Name="Snafu" Title="{Binding Bar,Mode=TwoWay}" />
I checked It..This will work..:)
Related
I have a listview's itemsource binded to a Observable collection of Animal class.
When the window loads up, listview displays all the items correctly.
But I have a button which deletes an item from the observablecollection which did not update the listview.
Expected Behaviour: Button click should delete first item in observable collection and update the UI
Observed Behaviour: Button click should deletes first item in observable collection but did not update the UI
public class Animal
{
public int Num { get; set; }
public string Name { get; set; }
}
public class ViewModel:INotifyPropertyChanged
{
private ObservableCollection<Animal> animals;
public ObservableCollection<Animal> Animals
{
get { return animals; }
set { animals = value; OnPropertyChanged("Animals"); }
}
public ViewModel()
{
Animals = new ObservableCollection<Animal>()
{
new Animal(){ Name="ASD", Num = 1},
new Animal(){ Name="XYZ", Num = 2},
};
}
public void Run()
{
Animals.RemoveAt(0);
}
public event PropertyChangedEventHandler PropertyChanged;
// Create the OnPropertyChanged method to raise the event
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
<Grid DataContext="{Binding Source={StaticResource ViewModelDataSource}}">
<Button Content="Button" HorizontalAlignment="Left" Height="20" Margin="70,285,0,0" VerticalAlignment="Top" Width="100" Click="Button_Click"/>
<ListView x:Name="mylistview" HorizontalAlignment="Left" Height="212" Margin="42,47,0,0" VerticalAlignment="Top" Width="446" ItemsSource="{Binding Animals}">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Label Content="{Binding Num}"/>
<Label Content="{Binding Name}"/>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
public partial class MainWindow : Window
{
private ViewModel vm;
public MainWindow()
{
InitializeComponent();
vm = new ViewModel();
}
private void Button_Click(object sender, System.Windows.RoutedEventArgs e)
{
vm.Run();
}
}
ListView uses DataContext="{Binding Source={StaticResource ViewModelDataSource}}.
In a Window you create another instance of a view model (vm = new ViewModel();). After that you have 2 different instances and collections. vm.Run(); removes item from collection which is not connected to view.
You need to work with one instance, so try to find the same resource, which is used in the view:
public MainWindow()
{
InitializeComponent();
vm = (ViewModel)this.FindResource("ViewModelDataSource");
}
Also DataContext setter can be simplified:
`DataContext="{StaticResource ViewModelDataSource}"`
it is preferable to follow MVVM aproach and get rid of code behind:
1] declare command property in a viewmodel
public ICommand RunCmd { get; private set; }
2] use some ready-made ICommand implementation, e.g. RelayCommand or DelegateCommand and initialize RunCmd property from viewmodel constructor:
RunCmd = new RelayCommand(Run);
3] bind Button to that command:
<Button Content="Button"
HorizontalAlignment="Left"
Height="20" Width="100" Margin="70,285,0,0"
VerticalAlignment="Top"
Command="{Binding RunCmd}"/>
note, that Click handler is removed
I am encountering a similar problem to what is described in this SO question. The suggested solution is to create a new WebBrowser Control for each now page (PDF) we wish to present (Overwriting the old WebBrowser control).
What is the correct way of creating a new control like that in MVVM? I trying to keep the VM ignorant about the implementation of the view.
Why does the VM need to know? Why can't the view just hook into an appropriate event (define one if you like, or just use the PropertyChanged) and recreate the control?
Create an interface in the ViewModel named IBrowserCreator, with a method called CreateBrowser().
Create a static class in the ViewModel named ViewHelper, and add to it a static property of type IBrowserCreator named BrowserCreator.
In the View layer, create a new class called BrowserCreator, which implements ViewModel.IBrowserCreator.
In the View initialization code, instantiate a BrowserCreator, and assign it to ViewModel.ViewHelper.BrowserCreator.
From your ViewModel, you should now be able to call:
ViewHelper.BrowserCreator.CreateBrowser()
Obviously this answer is a framework only, but it should give you the general idea. You'll need to implement the CreateBrowser method to suit your exact needs.
why not simply use a Datatemplate and let WPF do the rest?
create a usercontrol with the webbrowser. you have to add an attached property because you can not bind to source directly.
<UserControl x:Class="WpfBrowser.BrowserControl"
xmlns:WpfBrowser="clr-namespace:WpfBrowser" >
<Grid>
<WebBrowser WpfBrowser:WebBrowserUtility.BindableSource="{Binding MyPdf}"/>
</Grid>
</UserControl>
create a viewmodel which handle your uri
public class MyPdfVM
{
public Uri MyPdf { get; set; }
public MyPdfVM()
{
this.MyPdf = new Uri(#"mypdf path");
}
}
take your pageviewmodel, add the pdfviewmodel and take a contentcontrol in your view
public class MyPageViewmodel: INotifyPropertyChanged
{
private MyPdfVM _myPdfStuff;
public MyPdfVM MyPdfStuff
{
get { return _myPdfStuff; }
set { _myPdfStuff = value; this.NotifyPropertyChanged(()=>this.MyPdfStuff);}
}
public MyViewmodel()
{
this.MyPdfStuff = new MyPdfVM();
}
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged<T>(Expression<Func<T>> property)
{
var propertyInfo = ((MemberExpression)property.Body).Member as PropertyInfo;
if (propertyInfo == null)
{
throw new ArgumentException("The lambda expression 'property' should point to a valid Property");
}
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyInfo.Name));
}
}
window.xaml
<Window x:Class="WpfBrowser.MainWindow"
xmlns:WpfBrowser="clr-namespace:WpfBrowser"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<DataTemplate DataType="{x:Type WpfBrowser:MyPdfVM}">
<WpfBrowser:BrowserControl />
</DataTemplate>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="64*" />
<RowDefinition Height="247*" />
</Grid.RowDefinitions>
<Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="32,14,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
<ContentControl Grid.Row="1" Content="{Binding MyPdfStuff}"/>
</Grid>
</Window>
window.xaml.cs
public partial class MainWindow : Window
{
private MyViewmodel _data;
public MainWindow()
{
_data = new MyViewmodel();
InitializeComponent();
this.DataContext = _data;
}
private void button1_Click(object sender, RoutedEventArgs e)
{
this._data.MyPdfStuff = new MyPdfVM() { MyPdf = new Uri(#"your other pdf path for testing") };
}
}
when ever you change the MyPdfStuff Property the webbroswer update the pdf.
attached property
public static class WebBrowserUtility
{
public static readonly DependencyProperty BindableSourceProperty =
DependencyProperty.RegisterAttached("BindableSource", typeof(string), typeof(WebBrowserUtility), new UIPropertyMetadata(null, BindableSourcePropertyChanged));
public static string GetBindableSource(DependencyObject obj)
{
return (string)obj.GetValue(BindableSourceProperty);
}
public static void SetBindableSource(DependencyObject obj, string value)
{
obj.SetValue(BindableSourceProperty, value);
}
public static void BindableSourcePropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
WebBrowser browser = o as WebBrowser;
if (browser != null)
{
string uri = e.NewValue as string;
browser.Source = string.IsNullOrWhiteSpace(uri) ? null:new Uri(uri);
}
}
}
EDIT: added some code so you can see that if you chane the PDFViewmodel your browsercontrol show the new pdf.
I'm new in WPF and I have the following problem.
I have the following class with many properties , but here is only one property for example:
public class StatusData : INotifyPropertyChanged
{
private string m_statusText = String.Empty;
public StatusData()
{
m_statusText = "1234";
}
public string StatusText
{
get
{
return m_statusText;
}
set
{
if (m_statusText != value)
{
m_statusText = value;
NotifyPropertyChanged("StatusText");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Another component of the project changes StatusData and calls Update() function in MainWindow.
So, m_statusData of this MainWindow has changed and I want update the textbox with m_statusText accordingly.
public class MainWindow
{
private StatusData m_statusData = new StatusData();
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
grid1.DataContext = m_statusData ;
}
public void Update(StatusData newStatusData)
{
m_statusData = newStatusData;
}
}
Xaml code:
<Window x:Class="WpfApplicationUpdateTextBox.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Name="myWin"
xmlns:local="clr-namespace:WpfApplicationUpdateTextBox"
Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded" >
<Grid Name="grid1">
<TextBox Text="{Binding Path=StatusText}" Name="textBox1" />
</Grid>
</Window>
The question is : why the textBox is not updated withnewStatusData.StatusText?
Here, you are assigning the grid's DataContext to m_statusData:
grid1.DataContext = m_statusData ;
And here, you are reassigning m_statusData to something else:
m_statusData = newStatusData;
The problem is that this has no effect on grid1.DataContext, which was set to the previous instance of m_statusData.
In this case, doing grid1.DataContext = newStatusData should solve your problem. However, a better solution would be to create a StatusData property which returns m_statusData. You can then do a RaisePropertyChanged() on it when m_statusData changes.
private void Update(StatusData newStatusData)
{
StatusData = newStatusData;
}
public StatusData StatusData
{
get
{
return m_statusData;
}
set
{
m_statusData = value;
RaisePropertyChanged("StatusData");
}
}
... and then in your XAML, bind your Grid's DataContext to the StatusData property
Edit:
To bind the grid's data context to the StatusData property, you can do this in your XAML:
<Grid Name="grid1" DataContext="{Binding StatusData}">
<TextBox Text="{Binding Path=StatusText}" Name="textBox1" />
</Grid>
You will also need to set the initial DataContext of your window, to make all of the other databindings work (this is a little strange and non-standard, but it will do the trick):
this.DataContext = this;
Your class StatusData has only 1 property: StatusText. If this property is the only thing you want to change with this code:
m_statusData = newStatusData;
You can change it to this:
m_statusData.StatusText = newStatusData.StatusText;
This code will fire the PropertyChangedEvent of StatusData class and that will change TextBox value.
I have following code:
<Window x:Class="WpfApplication1.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">
<Grid>
<TextBox Text="{Binding Path=Name,
Mode=OneWayToSource,
UpdateSourceTrigger=Explicit,
FallbackValue=default text}"
KeyUp="TextBox_KeyUp"
x:Name="textBox1"/>
</Grid>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
private void TextBox_KeyUp(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
BindingExpression exp = this.textBox1.GetBindingExpression(TextBox.TextProperty);
exp.UpdateSource();
}
}
}
public class ViewModel
{
public string Name
{
set
{
Debug.WriteLine("setting name: " + value);
}
}
}
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
Window1 window = new Window1();
window.DataContext = new ViewModel();
window.Show();
}
}
I want to update source only when "Enter" key is pressed in textbox. This works fine. However binding updates source at program startup. How can I avoid this? Am I missing something?
The problem is, that DataBinding is resolved on the call of Show (and on InitializeComponent, but that is not important for you, because at that point your DataContext is not set yet). I don't think you can prevent that, but I have an idea for a workaround:
Do not set the DataContext before you call Show(). You can achieve this (for example) like this:
public partial class Window1 : Window
{
public Window1(object dataContext)
{
InitializeComponent();
this.Loaded += (sender, e) =>
{
DataContext = dataContext;
};
}
}
and:
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
Window1 window = new Window1(new ViewModel());
window.Show();
}
Change your Binding Mode to Default
<TextBox Text="{Binding Path=Name,
Mode=Default,
UpdateSourceTrigger=Explicit,
FallbackValue=default text}"
KeyUp="TextBox_KeyUp"
x:Name="textBox1"/>
Can you bind to a local variable like this?
SystemDataBase.cs
namespace WebWalker
{
public partial class SystemDataBase : Window
{
private string text = "testing";
...
SystemDataBase.xaml
<TextBox
Name="stbSQLConnectionString"
Text="{SystemDataBase.text}">
</TextBox>
??
Text is set to the local variable "text"
The pattern is:
public string Text {get;set;}
and the binding is
{Binding Text, RelativeSource={RelativeSource FindAncestor, AncestorType=Window}}
If you want the binding to update automatically you should make it a DependencyProperty.
I think 3.5 added ElementName to bindings, so the following is a little easier:
<Window x:Name="Derp" ...
<TextBlock Text="{Binding Text, ElementName=Derp}"/>
To bind to a local "variable" the variable should be:
A property, not a field.
Public.
Either a notifying property (suitable for model classes) or a dependency property (sutable for view classes)
Notifying property example:
public MyClass : INotifyPropertyChanged
{
private void PropertyType myField;
public PropertyType MyProperty
{
get
{
return this.myField;
}
set
{
if (value != this.myField)
{
this.myField = value;
NotifyPropertyChanged("MyProperty");
}
}
}
protected void NotifyPropertyChanged(String propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
}
Dependency property example:
public MyClass : DependencyObject
{
public PropertyType MyProperty
{
get
{
return (PropertyType)GetValue("MyProperty");
}
set
{
SetValue("MyProperty", value);
}
}
// Look up DependencyProperty in MSDN for details
public static DependencyProperty MyPropertyProperty = DependencyProperty.Register( ... );
}
If you're doing a lot of this, you could consider binding the DataContext of the whole window to your class. This will be inherited by default, but can still be overridden as usual
<Window DataContext="{Binding RelativeSource={RelativeSource Self}}">
Then for an individual components you can use
Text="{Binding Text}"
To bind a local variable which is present in your Window class it has to be :
1. Public property
2. A notifying property. For this your window class should implement INotifyPropertyChanged interface for this property.
Then in the constructor
public Assgn5()
{
InitializeComponent();
this.DataContext = this; // or **stbSQLConnectionString**.DataContext = this;
}
<TextBox
Name="stbSQLConnectionString"
Text="{Binding text}">
</TextBox>
Need to add the following line in the int constructor:
this.DataContext = this;
And use this in the XAML:
<TextBox Text = "{Binding SomeProperty}" />
Exmaple:
MainWindow.xaml.cs
public partial class MainWindow : Window
{
public string PersonName { get; set; }
public MainWindow()
{
InitializeComponent();
PersonName = "default";
this.DataContext = this;
}
void button1_Click(object sender, RoutedEventArgs args)
{
MessageBox.Show($"Hello {PersonName}");
}
}
MainWindow.xaml
<StackPanel>
<TextBox Name="textbox1"
Text="{Binding PersonName, Mode=TwoWay}"
/>
<Button Name="button1" Click="button1_Click" Content="Click Me" />
</StackPanel>