Update WPF with externalevent and MVVM schema - c#

I'm currently developping a new soft which analyze a lot of data on Revit.
I have my WPF View, my ViewModel and a long methode.
init.cs:
IExternalEventHandler handlerEvent = new FamilyAnalysis();
var familyAnalysisEvent = ExternalEvent.Create(handlerEvent);
Gui = new AnalysisView(familyAnalysisEvent);
Gui.Show();
AnalysisView.xaml.cs:
public AnalysisView(ExternalEvent externalEvent)
{
InitializeComponent();
Windows.SetLocation(this);
Language = System.Windows.Markup.XmlLanguage.GetLanguage(System.Threading.Thread.CurrentThread.CurrentCulture.Name);
DataContext = new AnalysisViewModel(externalEvent, this);
}
AnalysisViewModel.cs:
public ICommand StartAnalysisCommand
{
get
{
return _startAnalysisCommand ?? (_startAnalysisCommand = new RelayCommand(() =>
{
//Some check before then..
_externalEvent.Raise();
}));
}
}
during the _externalEvent.Raise() I would like to have a loading form updating the state of the methode.
I tried to search about dispatcher but I'm not sure how to do that and all my try didn't worked. The loading screen pop but the value are not getting updated.
Any advice ?

Related

ReportViewer in MVVM WPF

I'm building an MVVM Light WPF app using Visual Studio 2015. The app needs to display some SQL Server Reporting Services reports locally.
The following two solutions exist:
Using MS ReportViewer in WPF
Walkthrough: Using ReportViewer in a WPF Application
Though the first is MVVM, it's mixing UI with the view model. The second is pure code-behind.
Here's what the first example suggests:
WindowsFormsHost windowsFormsHost = new WindowsFormsHost();
reportViewer = new ReportViewer();
windowsFormsHost.Child = reportViewer;
this.Viewer = windowsFormsHost
Note that ReportViewer is a UI control. The second solution uses a code-behind file:
private void ReportViewer_Load(object sender, EventArgs e)
{
//...
}
Is there a way to embed a local SSRS report into a WPF app and follow good MVVM practices? Thank you.
Update: No need to be fanatical! If some code-behind is needed, I'm okay with it.
We use a view to select the report from a ComboBox and a button to run it. In the viewmodel, we have the reports' ComboBox bound to an ObservableCollection of report names and IDs. We then employ the MVVM Light Toolkit's Messaging class to send/receive "messages." Note that the base viewmodel, MyAppViewModelBase, inherits from Light Toolkit's ViewModelBase, which has the RaisePropertyChanged() defined.
Also note that we could pass the selected report's VM instead of the view's VM; that would be more efficient but will require modifications to this code. Then we'd use a base class for all the report VMs and a pattern-matching switch in the code-behind to select which report to run.
Here's the pertinent code for the viewmodel:
using GalaSoft.MvvmLight.Messaging;
public class ReportsViewModel : MyAppViewModelBase
{
public ReportsViewModel()
{
// Register a listener that receives the enum of the
// report that's ready. The message it receives has
// name "SsrsReportReady" with handler SsrsReportReady.
Messenger.Default.Register<Constants.Report>(this, "SsrsReportReady", SsrsReportReady);
// Other logic...
}
// Bound to a button to run the selected report
public ICommand RunReportRelayCommand =>
new RelayCommand(RunReport);
// Backing field for the selected report.
private ReportViewModel _selectedReportVm;
public ReportViewModel SelectedReportVm
{
get { return _selectedReportVm; }
set
{
if (Equals(value, _selectedReportVm)) return;
_selectedReportVm = value;
// Built-in method from Light Toolkit to
// handle INotifyPropertyChanged
RaisePropertyChanged();
}
}
private void RunReport()
{
// Send a message called "RunSSRSReport" with this VM attached as its data.
Messenger.Default.Send(this, "RunSSRSReport");
}
// Handler for report-ready
private void SsrsReportReady(Constants.Report obj)
{
ShowReport = true;
IsRunReportButtonEnabled = true;
RunReportButtonContent = Constants.BtnGenerateReport;
// View uses Material Design's Expander control.
// We expand/collapse sections of the view.
ExpandReport = true;
ExpandParameters = false;
}
}
In the code-behind of the view:
using GalaSoft.MvvmLight.Messaging;
public partial class ReportsView : UserControl
{
public ReportsView()
{
InitializeComponent();
// Register a listener for the "RunSSRSReport"
// message, called from our viewmodel. Its
// handler is RunSsrsReport and its data type
// is ReportsViewModel.
Messenger.Default.Register<ReportsViewModel>(this, "RunSSRSReport", RunSsrsReport);
DataContext = new ReportsViewModel();
}
// Handler to run the selected report.
private void RunSsrsReport(ReportsViewModel obj)
{
// Basic validation
if (obj.SelectedReportVm == null || obj.SelectedReportVm.Id.Equals(-1))
{
return;
}
// Ugly switch to run the correct report.
// It can be re-written with pattern matching.
switch (obj.SelectedReportVm.Id)
{
case (int)Constants.Report.ReportA:
RunReportA(obj);
break;
case (int)Constants.Report.ReportB:
RunReportB(obj);
break;
// other reports....
}
}
// Run the report using dataset and tableadapter.
// Modify to use your code for running the report.
private void RunReportA(ReportsViewModel reportsViewModel)
{
var dataSet = new ReportADataSet();
dataSet.BeginInit();
// We reference the ReportViewer control in XAML.
ReportViewer.ProcessingMode = ProcessingMode.Local;
ReportViewer.LocalReport.ShowDetailedSubreportMessages = true;
ReportViewer.LocalReport.DataSources.Clear();
var dataSource = new ReportDataSource
{
Name = "ReportA_DS",
Value = dataSet.uspReportA // Uses a stored proc
};
ReportViewer.LocalReport.DataSources.Add(dataSource);
ReportViewer.LocalReport.ReportEmbeddedResource =
"MyApp.Reports.ReportA.rdlc";
dataSet.EndInit();
new reportATableAdapter { ClearBeforeFill = true }
.Fill(dataSet.uspReportA);
// Send message back to viewmodel that the report is ready.
Messenger.Default.Send(Constants.Report.ReportA, "SsrsReportReady");
}
}
The report view has a WindowsFormsHost with name ReportViewer, referenced in above code-behind:
<WindowsFormsHost Width="Auto" Height="500">
<rv:ReportViewer x:Name="ReportViewer" />
</WindowsFormsHost>

Binding a HTML control into a stacklayout using xamarin forms

Being a newbie to Xamrin I am struggling to adding some HTML to a StackLayout via Xamarin Forms. I have tried quite a few things and had a Google around.
Firstly I can't work out which bindable object I am supposed to be using. As I cannot find a straight answer on Google/Xamarin I am going to assume this is not as easy I was hoping.
var nameEntry = new Label ();
nameEntry.SetBinding (Label.TextProperty, "Club.ClubName");
var webView = new WebView ();
webView.SetBinding ( ??? , "Club.Description");
var content = new StackLayout {
Children = {
nameEntry,
???
}
};
I am not sure if this is possible within Xamarin forms itself. Can anyone help?
I should point out my data for the form is being retrieved asynchronously on a remote json endpoint
protected override void OnAppearing ()
{
base.OnAppearing ();
if (ViewModel == null || ViewModel.IsLoading)
return;
ViewModel.LoadItemsCommand.Execute (Club.ClubId);
}
My remote json api contains, Description contatins a HTML snippet which I would like to use.
{
ClubName: "Stourbridge",
Description: "<p>This club meets every TWO weeks on a <b>Friday</b>.</p>"
...
}
Try the following example that will show how to do the bindings.
Note that you have to use a HtmlWebViewSource to achieve this, and bind the WebView.Source to this.
Clicking the button will change the view model and update the WebView appropriately to the newly changed text.
StackLayout objStackLayout = new StackLayout();
MyView objMyView = new MyView();
objMyView.MyHtml = "<html><head></head><body><h1>Title</h1><p>Some body text</p></body></html>";
HtmlWebViewSource objHtmlWebViewSource = new HtmlWebViewSource();
objHtmlWebViewSource.SetBinding(HtmlWebViewSource.HtmlProperty, "MyHtml");
objHtmlWebViewSource.BindingContext = objMyView;
WebView objWebview = new WebView();
objWebview.HorizontalOptions = LayoutOptions.FillAndExpand;
objWebview.VerticalOptions = LayoutOptions.FillAndExpand;
objWebview.Source = objHtmlWebViewSource;
Button objMyButton2 = new Button();
objMyButton2.Text="Change Html";
objMyButton2.Clicked+=((o2,e2)=>
{
objMyView.MyHtml = "<html><head></head><body><h1>Title</h1><p>Some body text that has changed.</p></body></html>";
});
objStackLayout.Children.Add(objMyButton2);
objStackLayout.Children.Add(objWebview);
The view model is just a simple one with a bindable property as below:-
public class MyView
: Xamarin.Forms.View
{
public static readonly BindableProperty MyHtmlProperty = BindableProperty.Create<MyView, string>(p => p.MyHtml, default(string));
public string MyHtml
{
get { return (string)GetValue(MyHtmlProperty); }
set { SetValue(MyHtmlProperty, value); }
}
}
Before clicking the button gives:-
After clicking the button, adjusts the view model, and automatically updates the control via the binding giving:-

Problems with Syncfusion GridTreeControl and Binding

I'm new to WPF and am using the Syncfusion Framework. I want to use the DataTreeControl to display a hierarchy of data which will be loaded and updated in a reoccuring interval. But for some reason it doesn't display the data.
Here's a snipped from my MainWindow.xaml
<syncfusion:TabItemExt Name="_tabItemTipps" Header="Tipps">
<syncfusion:GridTreeControl Name="_treeGrid"
BorderBrush="LightGray"
BorderThickness="0,0.5,0,0"
EnableHotRowMarker="False"
EnableNodeSelection="True"
ExpandStateAtStartUp="AllNodesExpanded"
ReadOnly="True"
SupportNodeImages="True"
VisualStyle="Metro"
ItemsSource="SoccerMarkets"
>
<!-- Code for GridTreeControl Columns -->
<syncfusion:GridTreeControl.Columns>
<syncfusion:GridTreeColumn HeaderText="Nation" MappingName="{Binding RoughCat}"></syncfusion:GridTreeColumn>
</syncfusion:GridTreeControl.Columns>
</syncfusion:GridTreeControl>
This the snippet from MainWindow.xaml.cs where the DataContext is set:
public MainWindow()
{
DataContext = this;
InitializeComponent();
SkinStorage.SetVisualStyle(_tabControl, "Metro");
_settingsVM = new AppSettingsVM();
_txtBetdaqUser.DataContext = _settingsVM;
_chkSystemActive.DataContext = _settingsVM;
_chkInSimulationMode.DataContext = _settingsVM;
_mechanic = new TippMechanic(_settingsVM);
_soccerMarketsVM = new SoccerMarketVM();
Task[] tasks = new Task[1];
tasks[0] = Task.Factory.StartNew(async () => await _mechanic.Init());// _mechanic.Init();
Task.WaitAll(tasks);
_soccerMarketsVM.SoccerMarkets = _mechanic.SoccerMarketManager.SoccerMarkets;
_treeGrid.DataContext = _soccerMarketsVM.SoccerMarkets;
}
My ViewModel (_soccerMarketsVM) is defined this way:
class SoccerMarketVM : ObservableObject
{
private ObservableCollection<SoccerMarket> _soccerMarkets;
public ObservableCollection<SoccerMarket> SoccerMarkets
{
get { return _soccerMarkets; }
set
{
if(_soccerMarkets != null)
_soccerMarkets.CollectionChanged -= _soccerMarkets_CollectionChanged;
_soccerMarkets = value;
_soccerMarkets.CollectionChanged += _soccerMarkets_CollectionChanged;
}
}
public SoccerMarketVM()
{
//_soccerMarkets = new ObservableCollection<SoccerMarket>();
//_soccerMarkets.CollectionChanged += _soccerMarkets_CollectionChanged;
}
void _soccerMarkets_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
Console.WriteLine(e.Action.ToString());
}
}
The Events for CollectionChanged are fired and I get the Console.Writeline output.
Does anyone see's something wrong here?
In GridTreeControl, you can populate the data using different ways. In your code snippet, ItemsSource defined without specifying the Binding keyword and the MappingName is defined with Binding keyword. But for itemssource, you need to specify binding and for mapping name, you can directly assign property name without specifying binding. Please refer the below UG link of data population in GridTreeControl,
Link:
http://help.syncfusion.com/ug/wpf/index.html#!Documents/addingthegridtreecontroltoawpfapplication.htm
Elavarasan M – Syncfusion Software.

Programatically create a Popup with a Child element initialised by Caliburn Micro

Windows.Media.Captures has a handy CameraCaptureUI class that can be instantiated as follows to show a dialog to the user to capture photos or videos:
// Create dialog to Capture Video
CameraCaptureUI dialog = new CameraCaptureUI();
dialog.VideoSettings.Format = CameraCaptureUIVideoFormat.Mp4;
StorageFile file = await dialog.CaptureFileAsync(CameraCaptureUIMode.Video);
if (file != null)
{
// Do something with file...
}
I would like to create my own custom audio capture class that works in a very similar way:
// Create dialog to Capture Audio
AudioCaptureUI dialog = new AudioCaptureUI();
StorageFile file = await dialog.CaptureFileAsync();
if (file != null)
{
// Do something with file...
}
To do the above, I created the following three files:
AudioCaptureUI - The class that a user instantiates to show the audio capture dialog
AudioCaptureView - UI View for the audio capture experience
AudioCaptureViewModel - ViewModel that contains all the audio capture logic
To create a full screen audio capture dialog, I have figured out that the best way is to use a Popup and set its child to the AudioCaptureView. The problem I have with this approach is that it is pushing me use a View-First pattern. Since I am using Caliburn Micro, I wanted to be able to use CM to instantiate a View by creating the ViewModel first.
What I currently have is something on the following lines:
public class AudioCaptureUI
{
private Popup _popup;
private TaskCompletionSource<StorageFile> _taskCompletionSource;
public IAsyncOperation<StorageFile> CaptureFileAsync()
{
// Force my View to be full screen
AudioCaptureView audioCaptureView = new AudioCaptureView
{
Width = Window.Current.Bounds.Width,
Height = Window.Current.Bounds.Height
};
// Creating View, instead of a ViewModel. Renders Caliburn Micro useless!
_popup = new Popup { Child = audioCaptureView };
if (_popup.Child != null)
{
SubscribeEvents();
_popup.IsOpen = true;
}
return AsyncInfo.Run(WaitForInput);
}
...
}
The above pattern works. However, I am forced to wire all my actions manually and cannot leverage Caliburn Micro's MVVM goodness.
How else should I instantiate a ViewModel programatically from my AudioCaptureUI class?
It is also important to highlight that I am working on a Windows Store app and using the WinRT CM port.
You could always port the WindowManager to WinRT in your own project. Looking at the source I don't think too much will need to change. https://caliburnmicro.codeplex.com/SourceControl/latest#src/Caliburn.Micro.Platform/net40/WindowManager.cs
You could bring over the Interface as well and use DI but for the sake of time here is the stand alone class. The main part for Model first binding is the ViewLocator.LocateForModel which returns the View from the ViewModel (aka the magic)
using System;
using System.Collections.Generic;
using Windows.UI.Xaml.Controls.Primitives;
namespace Caliburn.Micro
{
public class WindowManager
{
public virtual void ShowPopup(object rootModel, object context = null, IDictionary<string, object> settings = null)
{
var popup = CreatePopup(rootModel, settings);
var view = ViewLocator.LocateForModel(rootModel, popup, context);
popup.Child = view;
//popup.SetValue(View.IsGeneratedProperty, true);
ViewModelBinder.Bind(rootModel, popup, null);
Caliburn.Micro.Action.SetTargetWithoutContext(view, rootModel);
var activatable = rootModel as IActivate;
if (activatable != null)
{
activatable.Activate();
}
var deactivator = rootModel as IDeactivate;
if (deactivator != null)
{
popup.Closed += delegate { deactivator.Deactivate(true); };
}
popup.IsOpen = true;
//popup.CaptureMouse();
}
protected virtual Popup CreatePopup(object rootModel, IDictionary<string, object> settings)
{
var popup = new Popup();
ApplySettings(popup, settings);
return popup;
}
bool ApplySettings(object target, IEnumerable<KeyValuePair<string, object>> settings)
{
if (settings != null)
{
var type = target.GetType();
foreach (var pair in settings)
{
var propertyInfo = type.GetPropertyCaseInsensitive(pair.Key);
if (propertyInfo != null)
{
propertyInfo.SetValue(target, pair.Value, null);
}
}
return true;
}
return false;
}
}
}
Then all you need to do is create an instance and give it a ViewModel:
var windowManager = new WindowManager();
windowManager.ShowPopup(new MyPopupThingViewModel());
Note: I've only used this in an 8.1 app so not 100% sure if it will completely work with 8.0
You might have some success with the Caliburn.Micro WindowManager. There isn't a great deal about it in the official documentation (you're best off searching Google and the CM discussions). I've used it in one of my applications where I needed to host a particular ViewModel in a new window, and wanted to utilise all of the Caliburn.Micro goodness (and my existing Views).
Have a look at the Caliburn.Micro.IWindowManager interface, you'll see some handy methods that you can call from a WindowManager instance (depending on the popup type you're after).
public interface IWindowManager
{
bool? ShowDialog(object rootModel, object context = null, IDictionary<string, object> settings = null);
void ShowPopup(object rootModel, object context = null, IDictionary<string, object> settings = null);
void ShowWindow(object rootModel, object context = null, IDictionary<string, object> settings = null);
}
In my application, to pop up my a Window with my ViewModel of choice, I did something along these lines (your names inserted):
// Some basic Window settings.
dynamic settings = new ExpandoObject();
settings.Title = "Test Window";
settings.WindowStartupLocation = WindowStartupLocation.Manual;
settings.SizeToContent = SizeToContent.Manual;
settings.Width = 450;
settings.Height = 300;
var localAudioCaptureViewModel new AudioCaptureViewModel ();
WindowManagerFactory.WindowManager.ShowWindow(localAudioCaptureViewModel, null, settings); // I didn't require context (null)
Caliburn.Micro should resolve your Views to the correct ViewModels, and you're good to go.

Treeview is not inserting or showing data

I am using MonoDevelop to create a GUI but it doesn't contain a ListBox conrol. I read that Tree View is a good alternative so I'm trying to get it to work, but nothing appears to be added to the Tree View at all.
ListStore _store;
public MainWindow (): base (Gtk.WindowType.Toplevel)
{
Build ();
_store = new Gtk.ListStore (typeof(string));
lbErrors.Model = _store; // lbErrors is the Tree View
Error("err");
}
public void Error(string err)
{
var ii = _store.Append();
_store.SetValues(ii, err);
}
Can anyone spot the problem?
You need to set your table columns.
Try something like this:
var column = new TreeViewColumn ();
column.Title = "Column Name";
column.Clickable = false;
var renderer = new CellRendererText ();
column.PackStart (renderer, true);
column.AddAttribute (renderer, "text", 0);
lbErrors.AppendColumn (column);

Categories

Resources