I was thinking about displaying error messages to the user in a specific area of the shellview.
So I'm instantiating the ErrorViewModel in my ShellViewModel and it's the ErrorModel is displayed correct. The Textblock withing the ViewModel is displaying it's initialvalue as it should.
But if I pass a string via a public method from another ViewModel (e.g. LoginViewModel) the errorstring is passed to the ErrorViewModel and is also firing the NotifyOfPropertyChange(() => PublishErrorMsg) but the Textblock isnt changing.
Can't see why the content of the textblock won't change.
ErrorViewModel:
public class ErrorViewModel : Screen
{
private string publishErrorMsg;
public string PublishErrorMsg
{
get { return publishErrorMsg; }
set
{
publishErrorMsg = value;
NotifyOfPropertyChange(() => PublishErrorMsg);
}
}
public void ShowError(string msg) {
PublishErrorMsg = msg;
// MessageBox.Show(msg);
NotifyOfPropertyChange(() => PublishErrorMsg);
}
}
XAML ErrorView:
<UserControl x:Class="Views.ErrorView"
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:Views"
mc:Ignorable="d"
d:DesignHeight="40" d:DesignWidth="800" Background="White">
<Grid>
<DockPanel VerticalAlignment="Bottom" Height="40" Background="#FF474A57">
<TextBlock Text="{Binding PublishErrorMsg}"
Width="200" HorizontalAlignment="Center" VerticalAlignment="Center" Foreground="#FFE69393" FontSize="14">
</TextBlock>
</DockPanel>
</Grid>
Following the part which triggers the event:
public void LogIn() {
this.container.GetInstance<ErrorViewModel>().ShowError("User logged in");
try {
ResetPublishMsg();
ActiveUserModel.CreateIfAuthenticated(UserName, Password);
events.PublishOnUIThread(new LogOnEvent());
}
catch (Exception ex) {
this.container.GetInstance<ErrorViewModel>().PublishErrorMsg = ex.Message;
}
}
Thanks for help!
Maybe have you forgotten to subscribe to event ? see EventAggregator
public class ErrorViewModel : Screen, IHandle<LogOnEvent>
{
private readonly IEventAggregator _eventAggregator;
public ErrorViewModel(IEventAggregator eventAggregator) {
_eventAggregator = eventAggregator;
_eventAggregator.Subscribe(this);
}
public void Handle(LogOnEvent message) {
// Handle the message here.
}
}
Related
I created a WPF sample (using caliburn micro with MVVM pattern, no code-behind) with a view model and their related views:
ShellView.xaml and ShellViewModel.cs
The ShellView contains:
A ComobBox, which contains a list of string, if this combox selection is changed, it will raise comboBox1_SelectionChanged() in ShellViewModel.
A Button, if click this button, it will raise Button1_Click() to delete the first item of list in ShellViewModel.
My questions:
If I want to click the button without trigger comboBox1_SelectionChanged in view model, how to do that?
If it implemented in code-behind, I can do like this:
public void Button1_Click(object sender, EventArgs e)
{
comboBox1.SelectionChanged -= comboBox1_SelectionChanged;
MyCollection.RemoveAt(0);
comboBox1.SelectionChanged += comboBox1_SelectionChanged;
}
I have no idea how to achieve this in view model. The following is the code:
ShellView.xaml
<UserControl x:Class="WpfApp.Views.ShellView"
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:WpfApp.Views"
xmlns:cal="http://caliburnmicro.com"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height=" auto"/>
<RowDefinition Height=" auto"/>
</Grid.RowDefinitions>
<ComboBox Name="comboBox1" Grid.Row="0" ItemsSource="{Binding MyCollection}" SelectedValue="{Binding SelectMyListValue}"
cal:Message.Attach="[Event SelectionChanged]=[Action comboBox1_SelectionChanged($source,$eventArgs)]" />
<Button Name="Button1" Grid.Row="1" Content="Delete"
cal:Message.Attach="[Event Click]=[Action Button1_Click($source,$eventArgs)]" />
</Grid>
</UserControl>
ShellViewModel.cs
using Caliburn.Micro;
using System;
using System.Windows.Controls;
namespace WpfApp.ViewModels
{
public class ShellViewModel : Conductor<object>.Collection.OneActive
{
private BindableCollection<string> _myCollection = new BindableCollection<string>() { "item1", "item2"};
public BindableCollection<string> MyCollection
{
get => _myCollection;
set
{
_myCollection = value;
NotifyOfPropertyChange(() => MyCollection);
}
}
private string _selectMyListValue = "item1";
public string SelectMyListValue
{
get => _selectMyListValue;
set
{
_selectMyListValue = value;
NotifyOfPropertyChange(nameof(SelectMyListValue));
}
}
public void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
// Do something...
}
public void Button1_Click(object sender, EventArgs e)
{
MyCollection.RemoveAt(0);
}
}
}
Thank you in advance.
Your requirement can't be fully met, as when you remove the selected item from the collection a change of SelectedValue (to null) is inevitable.
Furthermore: You don't need to bind to the SelectionChanged event. You already have a binding to SelectedValue, so the setter of the bound property is called when the selection changes. This doesn't happen, when you remove a value from the collection that is not currently selected.
I would also recommend not to subscribe to the Clicked event of the button, but to bind an ICommand (added to your viewmodel) to the Command property of the button. An easy to use implementation would be the RelayCommand from the Windows Community Toolkit. You can read about it here: https://learn.microsoft.com/en-us/windows/communitytoolkit/mvvm/relaycommand. It also isn't difficult to implemnt a version on your own, if you don't want to use the whole toolkit.
Code sample:
public class RelayCommand : ICommand
{
private readonly Action<object?> execute;
private readonly Func<object?, bool> canExecute;
public RelayCommand(
Action<object?> execute,
Func<object?, bool>? canExecute = null)
{
this.execute = execute;
this.canExecute = canExecute ?? (_ => true);
}
public bool CanExecute(object? parameter) => this.canExecute(parameter);
public void Execute(object? parameter)
{
this.execute(parameter);
}
public event EventHandler? CanExecuteChanged;
}
// on your viewmodel add...
public ICommand RemoveFirstItemCommand { get; set; }
private void RemoveFirstItem(object? param)
{
if (this.Items.Count > 0)
{
this.Items.RemoveAt(0);
}
}
// ...and in the constructor init the command
this.RemoveFirstItemCommand = new RelayCommand(this.RemoveFirstItem);
I got a solution which achieved the goal, but I'm not sure if it's the right way.
There is a "Microsoft.Xaml.Behaviors" which provided "Interaction.Triggers" that contains "ComparisonCondition". I can use it to bind a value to determine the EventCommand is raised or not.
I updated the code as following:
ShellViewModel.cs
using Caliburn.Micro;
using System;
using System.Windows.Controls;
using WpfApp.Commands;
namespace WpfApp.ViewModels
{
public class ShellViewModel : Conductor<object>.Collection.OneActive
{
private bool _IsEnableSelectionChangedCommand = true;
public bool IsEnableSelectionChangedCommand
{
get => _IsEnableSelectionChangedCommand;
set
{
_IsEnableSelectionChangedCommand = value;
NotifyOfPropertyChange(() => IsEnableSelectionChangedCommand);
}
}
private BindableCollection<string> _myCollection = new BindableCollection<string>() { "item1", "item2"};
public BindableCollection<string> MyCollection
{
get => _myCollection;
set
{
_myCollection = value;
NotifyOfPropertyChange(() => MyCollection);
}
}
private string _selectMyListValue = "item1";
public DelegateCommand<object> DoSelectionChangedCommand { get; }
public ShellViewModel()
{
DoSelectionChangedCommand = new DelegateCommand<object>(comboBox1_SelectionChanged, CanExecute);
}
private bool CanExecute(object param)
{
return true;
}
private void comboBox1_SelectionChanged(object param)
{
SelectionChangedEventArgs e = param as SelectionChangedEventArgs;
ComboBox item = e.Source as ComboBox;
// Do something...
}
public string SelectMyListValue
{
get => _selectMyListValue;
set
{
_selectMyListValue = value;
NotifyOfPropertyChange(nameof(SelectMyListValue));
}
}
public void Button1_Click(object sender, EventArgs e)
{
IsEnableSelectionChangedCommand = false;
MyCollection.RemoveAt(0);
IsEnableSelectionChangedCommand = true;
}
}
}
ShellView.xaml
<UserControl x:Class="WpfApp.Views.ShellView"
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:cal="http://caliburnmicro.com"
xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
xmlns:cmd="clr-namespace:WpfApp.Commands"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height=" auto"/>
<RowDefinition Height=" auto"/>
</Grid.RowDefinitions>
<ComboBox Name="comboBox1" Grid.Row="0" ItemsSource="{Binding MyCollection}" SelectedValue="{Binding SelectMyListValue}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<cmd:EventCommand Command="{Binding DoSelectionChangedCommand}" />
<i:Interaction.Behaviors>
<i:ConditionBehavior>
<i:ConditionalExpression>
<i:ComparisonCondition LeftOperand= "{Binding IsEnableSelectionChangedCommand}" Operator="Equal" RightOperand="True"/>
</i:ConditionalExpression>
</i:ConditionBehavior>
</i:Interaction.Behaviors>
</i:EventTrigger>
</i:Interaction.Triggers>
</ComboBox>
<Button Name="Button1" Grid.Row="1" Content="Delete"
cal:Message.Attach="[Event Click]=[Action Button1_Click($source,$eventArgs)]" />
</Grid>
</UserControl>
I have a main window that hosts 2 user controls using ContentControl. Inside main window view model the Person model is instantiated and passed to both user controls with DI. My requirement is if the property First Name is edited in User Control 2 then this need to be reflected back in User Control 1 First Name property. Code is attached.
ShellViewModel (Main Window)
public class ShellViewModel : Screen
{
public IPersonModel _personModel { get; }
private IPeopleService _peopleService;
public UserControl1ViewModel UserControl1VM { get; set; }
public UserControl2ViewModel UserControl2VM { get; set; }
public ShellViewModel(IPersonModel personModel, IPeopleService peopleService)
{
_personModel = personModel;
_peopleService = peopleService;
_personModel = _peopleService.GetPersonInfo(1);
UserControl1VM = new UserControl1ViewModel(_personModel);
UserControl2VM = new UserControl2ViewModel(_personModel);
}
}
public class UserControl1ViewModel : PropertyChangedBase
{
private IPersonModel Model;
public UserControl1ViewModel(IPersonModel model)
{
Model = model;
}
public string FirstName
{
get
{
return Model.FirstName;
}
set
{
NotifyOfPropertyChange(() => FirstName);
NotifyOfPropertyChange(() => FullName);
}
}
public string LastName
{
get { return Model.LastName; }
set
{
NotifyOfPropertyChange(() => LastName);
NotifyOfPropertyChange(() => FullName);
}
}
public string FullName => $"{FirstName} {LastName}";
}
public class UserControl2ViewModel : PropertyChangedBase
{
private IPersonModel _model;
public UserControl2ViewModel(IPersonModel model)
{
_model = model;
}
public string FirstName
{
get
{
return _model.FirstName;
}
set
{
_model.FirstName = value;
NotifyOfPropertyChange(() => FirstName);
//NotifyOfPropertyChange(() => FullName);
}
}
public string LastName
{
get { return _model.LastName; }
set
{
_model.LastName = value;
NotifyOfPropertyChange(() => LastName);
//NotifyOfPropertyChange(() => FullName);
}
}
}
UserControl2 view:
UserControl x:Class="UI.Views.UserControl2View"
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:UI.Views"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="400">
<Grid>
<StackPanel Margin="12">
<TextBox Text="{Binding FirstName, Mode=TwoWay}" Margin="5"/>
<TextBox Text="{Binding LastName, Mode=TwoWay}" Margin="5"/>
<TextBlock Text="{Binding FirstName, Mode=OneWay}" Margin="5"/>
</StackPanel>
</Grid>
</UserControl>
UserControl1 View:
<UserControl x:Class="UI.Views.UserControl1View"
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:UI.Views"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="350">
<Grid>
<StackPanel Margin="10">
<TextBlock Text="{Binding FirstName}" Margin="5"/>
<TextBlock Text="{Binding LastName}" Margin="5"/>
<TextBlock Text="{Binding FullName}" Margin="5"/>
</StackPanel>
</Grid>
</UserControl>
You need to make use of EventAggregator pattern implementation in Caliburn Micro to notify instances of another ViewModel which doesn't have a direct reference in the current ViewModel.
To do so, you need to begin by defining a Message Type, which could be used to uniquely identify the particular change.
public class NotifyPersonModelChangeMessage
{
public IPersonModel PersonModel { get; set; }
}
The next step involves publishing a message of type NotifyPersonModelChangeMessage from the UserControl2ViewModel when the desired property changes in it.
For example,
public class UserControl2ViewModel : PropertyChangedBase
{
private IPersonModel Model;
private IEventAggregator _eventAggregator;
public UserControl2ViewModel(IPersonModel model,IEventAggregator eventAggregator)
{
Model = model;
_eventAggregator = eventAggregator;
_eventAggregator.SubscribeOnUIThread(this);
}
public string FirstName
{
get
{
return Model.FirstName;
}
set
{
Model.FirstName = value;
NotifyOfPropertyChange(nameof(FirstName));
NotifyOfPropertyChange(nameof(FullName));
NotifyNameChange();
}
}
private void NotifyNameChange()
{
_eventAggregator.PublishOnUIThreadAsync(new NotifyPersonModelChangeMessage { PersonModel = Model });
}
}
This would publish a message to the Event Aggregator implementation. The next step would be to ensure the UserControl1ViewModel subscribes to the message and makes the changes accordingly. This could be done using implementation of IHandle<T> interface of Caliburn Micro
public class UserControl1ViewModel : PropertyChangedBase, IHandle<NotifyPersonModelChangeMessage>
{
private IPersonModel _model;
public UserControl1ViewModel(IPersonModel model, IEventAggregator eventAggregator)
{
_model = model;
eventAggregator.SubscribeOnUIThread(this);
}
public Task HandleAsync(NotifyPersonModelChangeMessage message, CancellationToken cancellationToken)
{
_model = message.PersonModel;
NotifyOfPropertyChange(nameof(FirstName));
NotifyOfPropertyChange(nameof(LastName));
return Task.CompletedTask;
}
// rest of the class
}
HandleAsync method would be invoked each time a message of type NotifyPersonModelChangeMessage is published to the EventAggregator since we have subscribed to the EventAggregator and is listening for the particular message type.
You could read more on EventAggregator in the official documentation of Caliburn Micro
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
I've been looking for hours but I can't find anything useful. Any help appreciated!
I'm writing a Kinect application using WPF with the Coding4Fun toolkit and the MVVM pattern.
I'd like to put all my kinect related logic in my ViewModel and bind those methods to a HoverButton (found in the C4F toolkit).
A normal button had the 'Command' property, However the HoverButton does not.
So in short:
I want to bind the click event of a HoverButton to a method in my ViewModel.
My XAML:
<Window x:Class="KinectTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:fun="clr-namespace:Coding4Fun.Kinect.Wpf.Controls;assembly=Coding4Fun.Kinect.Wpf" Title="MainWindow" Height="350" Width="525"
Loaded="WindowLoaded"
Closed="WindowClosed"
Cursor="None"
>
<Grid Name="MainGrid" MouseMove="GridHoverMouseMove" DataContext="_viewModel">
<Canvas Name="SkeletonCanvas" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Background="Black">
<fun:HoverButton Name="KinectUp" ImageSource="/Images/blue_glass.png" ActiveImageSource="/Images/blue_glass.png" ImageSize="100" Canvas.Top="26" TimeInterval="1000">
</fun:HoverButton>
<fun:HoverButton Name="KinectDown" ImageSource="/Images/red_glass.png" ActiveImageSource="/Images/red_glass.png" ImageSize="100" Canvas.Bottom="26" TimeInterval="1000"/>
</Canvas>
<Image Name="ColorImage" VerticalAlignment="Bottom" HorizontalAlignment="Right" Width="120" Height="120"></Image>
<TextBlock Name="Notification" Foreground="White" FontSize="50" VerticalAlignment="Top" HorizontalAlignment="Stretch" TextAlignment="Center" Text="{Binding Path=Notification, Mode=TwoWay}"></TextBlock>
<Canvas Name="CanvMouse" Background="Transparent" VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
<Image Name="imgMouse" Width="70" Source="/Images/handround_green.png"></Image>
</Canvas>
</Grid>
</Window>
My ViewModel:
internal class MainViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public ICommand KinectUpClick { get; private set; }
public ICommand KinectDownClick { get; private set; }
private string _notification = "Hello";
public SensorHelper SensorHelper { get; set; }
public string Notification
{
get { return _notification; }
set
{
_notification = value;
PropertyChanged(this, new PropertyChangedEventArgs("Notification"));
}
}
public MainViewModel()
{
KinectUpClick = new RelayCommand(PerformKinectUpClick, CanKinectUpClick);
KinectDownClick = new RelayCommand(PerformKinectDownClick, CanKinectDownClick);
}
private bool CanKinectUpClick(object parameter)
{
return SensorHelper.CanMoveUp;
}
private bool CanKinectDownClick(object parameter)
{
return SensorHelper.CanMoveDown;
}
private void PerformKinectUpClick(object parameter)
{
ThreadPool.QueueUserWorkItem((o) =>
{
Notification = "Kinect goes up!";
SensorHelper.MoveAngle(5);
Notification = "Kinect ready...";
});
}
private void PerformKinectDownClick(object parameter)
{
ThreadPool.QueueUserWorkItem((o) =>
{
Notification = "Kinect goes down!";
SensorHelper.MoveAngle(-5);
Notification = "Kinect ready...";
});
;
}
}
}
My Code-behind:
public partial class MainWindow : Window
{
private readonly MainViewModel _viewModel;
private SensorHelper _sensorHelper;
public MainWindow()
{
InitializeComponent();
_viewModel = new MainViewModel();
MainGrid.DataContext = _viewModel;
}
private void WindowLoaded(object sender, RoutedEventArgs e)
{
try
{
_sensorHelper = new SensorHelper();
}
catch (Exception exception)
{
MessageBox.Show(exception.Message);
}
_viewModel.SensorHelper = _sensorHelper;
_sensorHelper.InitializeSkeleton(ref SkeletonCanvas);
//_sensorHelper.CaptureMouse(CanvMouse);
_sensorHelper.InitializeColorFrame(ColorImage);
_sensorHelper.StartKinect();
}
private void WindowClosed(object sender, EventArgs eventArgs)
{
_sensorHelper.StopKinect();
}
private void GridHoverMouseMove(object sender, MouseEventArgs e)
{
imgMouse.SetValue(Canvas.LeftProperty, e.GetPosition(CanvMouse).X - imgMouse.ActualWidth/2);
imgMouse.SetValue(Canvas.TopProperty, e.GetPosition(CanvMouse).Y - imgMouse.ActualHeight/2);
MouseHelper.CheckButton(KinectUp, imgMouse);
MouseHelper.CheckButton(KinectDown, imgMouse);
}
}
Okay, very simple, what you'll have to do is bind an ICommand/Command to an Event by using an EventToCommand which can be found in the MVVMLight Toolkit.
You can use Blend for that as well
Simple example :
<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:GalaSoft_MvvmLight_Command="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.WPF4"
x:Class="TestProject.Window5"
x:Name="Window"
Title="Window5"
Width="640" Height="480">
<Grid x:Name="LayoutRoot">
<Button Content="Button" HorizontalAlignment="Left" Height="69" Margin="92,117,0,0" VerticalAlignment="Top" Width="206">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<GalaSoft_MvvmLight_Command:EventToCommand Command="{Binding Kinect.MyCommand, Source={StaticResource Locator}}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
</Grid>
</Window>
today I getting crazy while trying to do, what I think, is simple thing.
I want to be able to create my usercontrol, and use it in my column template in my datagrid
I have searched and tried several combinations, and nothing appear to work
Can anyone help me?
public class User
{
public string Name { get; set; }
public bool IsValid { get; set; }
}
partial class MyControl : UserControl
{
private string _value;
public string Value
{
get { return _value; }
set { _value = value;
txt.Text = value;
}
}
public MyControl()
{
InitializeComponent();
}
}
<Grid x:Name="LayoutRoot" Background="White">
<TextBlock x:Name="txt" Text="[undefined]"></TextBlock>
</Grid>
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
var items = new List<User>();
items.Add(new User{Name = "user 1", IsValid = true});
items.Add(new User { Name = "user 2", IsValid = false });
myGrid.ItemsSource = items;
}
}
<Grid x:Name="LayoutRoot" Background="White">
<sdk:DataGrid x:Name="myGrid" AutoGenerateColumns="False" IsReadOnly="True">
<sdk:DataGrid.Columns>
<sdk:DataGridTemplateColumn Header="Name">
<sdk:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<SilverlightApplication1:MyControl Value="{Binding Name}"></SilverlightApplication1:MyControl>
<!--<TextBlock Text="{Binding Name}"></TextBlock>-->
</DataTemplate>
</sdk:DataGridTemplateColumn.CellTemplate>
</sdk:DataGridTemplateColumn>
</sdk:DataGrid.Columns>
</sdk:DataGrid>
</Grid>
Edited:
I also tried the following, but I get no results on my grid:
<Grid x:Name="LayoutRoot" Background="White">
<TextBlock x:Name="txt" Text="{Binding Value}"></TextBlock>
</Grid>
public partial class MyControl : UserControl
{
public DependencyProperty ValueProperty =
DependencyProperty.Register("Value",
typeof(string),
typeof(MyControl),
new PropertyMetadata(OnValueChanged));
public string Value
{
get
{
return (string)GetValue(ValueProperty);
}
set
{
SetValue(ValueProperty, value);
NotifyPropertyChanged("Value");
}
}
private static void OnValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((MyControl) d).Value = (String)e.NewValue; //ERROR: here I got always empty string
}
public MyControl()
{
InitializeComponent();
}
}
The reason why your first code didn't work is simple. To be able to bind the "Value" property on your "MyControl" (Value={Binding Name}), it has to be a Dependency Property. which you fixed in your second bit of code.
Here's what I did (and that worked well):
<UserControl x:Class="BusinessApplication8_SOF_Sandbox.Controls.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"
d:DesignHeight="300" d:DesignWidth="400" Name="myControl">
<Grid x:Name="LayoutRoot" Background="White">
<TextBlock Name="textBlock" Text="{Binding Value, ElementName=myControl}"/>
</Grid>
</UserControl>
For the rest, I used your code.
Another possibility, which should be OK in case you only want the data to flow in one direction ("One Way" from source to target), as it is the case when using the TextBlock control is to update the Text property in the "OnValueChanged". here's the code for the Value property:
public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register("Value", typeof(string), typeof(MyControl),
new PropertyMetadata("", OnValueChanged));
public string Value
{
get { return (string)GetValue(ValueProperty); }
set { SetValue(ValueProperty, value); }
}
private static void OnValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var target = (MyControl)d;
var oldValue = (string)e.OldValue;
var newValue = target.Value;
target.OnValueChanged(oldValue, newValue);
}
protected virtual void OnValueChanged(string oldValue, string newValue)
{
textBlock.Text = newValue;
}
and you can remove the binding in xaml:
<TextBlock Name="textBlock" />
this worked for me as well.
Hope this helps ;)
you need to implement the INotifyPropertyChanged interface in your User class so that bound user controls are aware if any of the bound properties change. See the following page with the details how to implement it : http://www.silverlightshow.net/tips/How-to-implement-INotifyPropertyChanged-interface.aspx
As you can see you need to implement the interface and in the setters raise the event OnPropertyChanged
Then it should work with your bindings.
Best,
Tim