Webview Navigation causes freezing on winrt (non x86) - c#

When using webview.navigate(url), the entire app freezes up. It's noticeable on x86 chips, but it completely freezes up tablets for close to 50 seconds.
I've tried many many things to try to marshall the thread, but absolutely nothing makes it better.
Any advice?
Here is the xaml and c#
<Page
x:Class="WebviewSample.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:WebviewSample"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"></ColumnDefinition>
<ColumnDefinition Width="*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid Grid.Column="0">
<ListView x:Name="listView" ItemsSource="{Binding}" SelectionChanged="ListView_OnSelectionChanged">
</ListView>
</Grid>
<Grid Grid.Column="1">
<WebView x:Name="webView"></WebView>
</Grid>
</Grid>
</Page>
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace WebviewSample
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached. The Parameter
/// property is typically used to configure the page.</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
var itemsList = new List<ListViewItem>();
for (var i = 0; i < 300; i++)
{
var listViewItem = new ListViewItem {Content = "Click Me!"};
itemsList.Add(listViewItem);
}
listView.DataContext = itemsList;
}
private void ListView_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
webView.Navigate(new Uri("http://online.wsj.com/article/SB10001424127887324299104578529112289298922"));
}
}
}

Related

Enter or over events are not fired when drag and drop is done on UWP

I'm making a desktop app with UWP for Windows. I was making drag and drop features, but it doesn't work. When I drag a file, it keeps showing "Not allowed" symbol,🚫. Drag events and over events seem not to be fired. Any help is greatly appreciated. I'm not running Visual Studio 2022 as an admin.
Mainpage.xamc.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
namespace XML2PDFConverter
{
/// <summary>
/// Starting from a blank page.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
private void BackgroundGrid_DragEnter(object sender, DragEventArgs e)
{
e.AcceptedOperation = Windows.ApplicationModel.DataTransfer.DataPackageOperation.Move;
}
private async void BackgroundGrid_Drop(object sender, DragEventArgs e)
{
if (e.DataView.Contains(Windows.ApplicationModel.DataTransfer.StandardDataFormats.StorageItems))
{
var items = await e.DataView.GetStorageItemsAsync();
var filePaths = items.Select(x => x.Path).ToList();
}
}
private void BackgroundGrid_DragOver(object sender, DragEventArgs e)
{
e.AcceptedOperation = Windows.ApplicationModel.DataTransfer.DataPackageOperation.Move;
}
}
}
MainPage.xaml
<Page
x:Class="XMLToPDFConverter.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="XMLToPDFConverter"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Grid x:Name="BackgroundGrid" AllowDrop="True" DragEnter="BackgroundGrid_DragEnter" Drop="BackgroundGrid_Drop" DragOver="BackgroundGrid_DragOver" />
</Page>
The problem is, that your grid does not have a background color. It is enought to set the background color to transparent and it will work as expected:
<Grid x:Name="BackgroundGrid" Background="Transparent" AllowDrop="True" DragEnter="BackgroundGrid_DragEnter" Drop="BackgroundGrid_Drop" DragOver="BackgroundGrid_DragOver" />

simulate AngularJS button click in c# uwp app

I am trying to create an app that automatically logs me into a webpage.
The page is not mine so I cannot see the code behind it.
http://pcc.magister.net (the page after the first notification screen)
Now I've managed to insert the username and password but I just cannot seem to be capable of triggering a click on the button in the page. I get as far as this :
var functionString = string.Format(#"document.getElementsByClassName('primary-btn ripple')[0].click();");
await Display.InvokeScriptAsync("eval", new string[] { functionString });
But I am getting nothing but errors. 'System.Exception' in System.Private.CoreLib.ni.dll and a 0x80020101 event that is a general javascript error.
The button in DOM explorer looks like this :
<mg-button is-loading="$ctrl.isLoading" caption="doorgaan">
<button class="primary-button ripple" type="submit" ng-class="{'active': $ctrl.isLoading}">
</button></mg-button>
Anybody smarter than me who sees what I'm doing wrong here ?
Here is a minimal c# :
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Diagnostics;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace Test
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
Display.Navigate(new Uri("http://pcc.magister.net/"));
}
private async void NewPageLoaded(WebView sender, WebViewNavigationCompletedEventArgs args)
{
string functionString = "";
if (Display.Source.AbsolutePath.ToString() == "/account/login")
{
functionString = String.Format("document.getElementById('username').innerText = 'testuser'");
try
{
await Display.InvokeScriptAsync("eval", new string[] { functionString });
}
catch
{
//
}
functionString = string.Format("document.getElementsByClassName('primary-btn ripple')[0].click();");
try
{
await Display.InvokeScriptAsync("eval", new string[] { functionString });
}
catch (Exception ezz)
{
Debug.WriteLine("There was an exception!" + ezz);
}
}
}
}
}
And a minimal XAML :
<Page
x:Class="Test.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Test"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" Margin="0,0,0,0" Name="mainGrid">
<WebView Margin="0,0,0,0" Name="Display" NavigationCompleted="NewPageLoaded"/>
</Grid>
</Page>

populate images from picture library to ListView in Windows 10 App

i am trying to show all images from default picture library to ListView in windows app but i am only able to show the names of images not the all images from the folder, here is my code.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.UI.Xaml.Media.Imaging;
using Windows.Storage.Streams;
using Windows.Storage;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace ListView
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
showall();
}
public async void showall()
{
IReadOnlyList<StorageFile> file = await KnownFolders.PicturesLibrary.GetFilesAsync();
foreach (StorageFile file1 in file)
{
list.Items.Add(file1.Name);
}
}
here is the xaml code...
<Page
x:Class="ListView.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:ListView"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<StackPanel>
<StackPanel HorizontalAlignment="Left" Width="350" Height="350">
<ListView Width="300" Height="300" Name="list" SelectionChanged="list_SelectionChanged">
<Image Width="200" Height="200" Name="img"></Image>
</ListView>
</StackPanel>
<StackPanel VerticalAlignment="Top">
<Image Width="300" Height="300" Name="img1" />
<TextBlock Width="300" Height="30" Name="txt1" />
</StackPanel>
</StackPanel>
</Grid>
There is no automatic conversion from StorageFile names to images.
You'll need two things, first a DataTemplate with an Image control in your ListView:
<ListView x:Name="list">
<ListView.ItemTemplate>
<DataTemplate>
<Image Source="{Binding}"/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Second, BitmapImages created from the StorageFiles, which are added to the Items collection instead of the file names:
public MainPage()
{
InitializeComponent();
Loaded += OnLoaded;
}
private async void OnLoaded(object sender, RoutedEventArgs e)
{
list.Items.Clear();
var files = await KnownFolders.PicturesLibrary.GetFilesAsync();
foreach (var file in files)
{
var bitmap = new BitmapImage();
using (var stream = await file.OpenReadAsync())
{
await bitmap.SetSourceAsync(stream);
}
list.Items.Add(bitmap);
}
}
Note also that loading is done in a Loaded event handler instead of directly calling an async method without awaiting it. Event handlers are the only methods that can safely be async void and not be awaited.
While Clemens' approach will work for you, I would like to show you a different approach. Using ViewModels.
Here is a PicturesViewModel:
public class PicturesViewModel
{
public ObservableCollection<ImageSource> MyImages { get; }
= new ObservableCollection<ImageSource>();
public async Task GetImages()
{
var files = await KnownFolders.PicturesLibrary.GetFilesAsync();
foreach (var file in files)
{
using (var stream = await file.OpenReadAsync())
{
BitmapImage image = new BitmapImage();
await image.SetSourceAsync(stream);
MyImages.Add(image);
}
}
}
}
Usually if it is a synchronous activity, you can write your logic in constructor. Since this is asynchronous, i am using another method in my view model to load a List of BitmapImages
Now in your MainPage_Loaded (a handler method of the MainPage's Loaded event as shown in the other answer) you need to do this:
private async void MainPage_Loaded(object sender, RoutedEventArgs e)
{
var viewModel = new PicturesViewModel();
DataContext = viewModel;
await viewModel.GetImages();
}
And your ListView is just Binding
<ListView ItemsSource="{Binding MyImages}">
<ListView.ItemTemplate>
<DataTemplate>
<Image Source="{Binding}"/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>

Binding to User Control Properties in an Items Control

Can someone tell me why the way I am binding data here does not work? I was able to do this fine with using a GridView. I am not sure why the data is not being passed to the user control here, in addition it compiles fine and shows the user controls with there default text
Main.xaml.cs:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace ItemsControlSample
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached. The Parameter
/// property is typically used to configure the page.</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
PopulateData();
}
public class someKindaOfDataHolder
{
public string Text1;
public string Text2;
}
private void PopulateData()
{
List<someKindaOfDataHolder> dataAndStuff = new List<someKindaOfDataHolder>();
for (int i = 0; i < 5; ++i)
{
dataAndStuff.Add(new someKindaOfDataHolder()
{
Text1 = "data spot 1: " + i.ToString(),
Text2 = "data spot 2: " + (i + 2).ToString()
});
}
ListOfAUserControls.ItemsSource = dataAndStuff;
}
}
}
Main.xaml
<Page
x:Class="ItemsControlSample.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:ItemsControlSample"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
<ScrollViewer>
<ItemsControl x:Name="ListOfAUserControls" ItemsSource="{Binding}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<local:CustomUserControl DynamicText1Text="{Binding Text1}" DynamicText2Text="{Binding Text2}" Margin="0,0,10,0"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="100,46,-50,0"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</ScrollViewer>
</Grid>
</Page>
CustomUserControl.xaml.cs:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236
namespace ItemsControlSample
{
public sealed partial class CustomUserControl : UserControl
{
public static readonly DependencyProperty DynamicText1Property =
DependencyProperty.Register("DynamicText1Text", typeof(string), typeof(CustomUserControl), new PropertyMetadata(null, OnDynamicText1PropertyChanged));
public string DynamicText1Text
{
get { return (string)GetValue(DynamicText1Property); }
set { SetValue(DynamicText1Property, value); }
}
public static readonly DependencyProperty DynamicText2Property =
DependencyProperty.Register("DynamicText2Text", typeof(string), typeof(CustomUserControl), new PropertyMetadata(null, OnDynamicText2PropertyChanged));
public string DynamicText2Text
{
get { return (string)GetValue(DynamicText2Property); }
set { SetValue(DynamicText2Property, value); }
}
public CustomUserControl()
{
this.InitializeComponent();
}
private static void OnDynamicText1PropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var obj = d as CustomUserControl;
obj.DynamicText1.Text = e.NewValue.ToString();
}
private static void OnDynamicText2PropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var obj = d as CustomUserControl;
obj.DynamicText2.Text = e.NewValue.ToString();
}
}
}
CustomUserControl.xaml:
<UserControl
x:Class="ItemsControlSample.CustomUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:ItemsControlSample"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="800"
d:DesignWidth="800">
<Grid Background="Blue">
<Grid.RowDefinitions>
<RowDefinition Height="6*"/>
<RowDefinition Height="2*"/>
</Grid.RowDefinitions>
<Image Source="ms-appx:///Assets/MSIcon.png" />
<StackPanel Grid.Row="1" Margin="25">
<TextBlock Text="Obay" FontSize="45" />
<TextBlock x:Name="DynamicText1" Text="DynamicText1" FontSize="35" />
<TextBlock x:Name="DynamicText2" Text="DynamicText2" FontSize="35" />
</StackPanel>
</Grid>
</UserControl>
Thanks!
You need to set the DataContext somewhere. Without it - your bindings have no context and they fail (look at the Output window in VS when debugging Debug builds to see binding errors). You are setting ItemsSource="{Binding}" where the binding has no context.
Then again - you are overriding the ItemsSource elsewhere with your "ListOfAUserControls.ItemsSource = dataAndStuff;" call, so that is likely not the issue causing your problem in the end. The DataContext of an item in an ItemsControl should be set automatically to an item in the ItemsSource collection.
Another problem that might block you there is that someKindaOfDataHolder.Text1 in your case is a field and it should be a property to work with bindings - try this instead:
public string Text1 { get; set; }

WPF Databinding Question

I've written a very short app in which I'm trying to achieve the following : have the CheckBox change its state from code. I've wired up the INotifyPropertyChanged interface and was expecting to see some results but apparently the app does nothing. Is there something wrong with the databinding?
Window1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;
namespace WpfTEST
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window, INotifyPropertyChanged
{
public Window1()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(Window1_Loaded);
this.PropertyChanged += new PropertyChangedEventHandler(Window1_PropertyChanged);
}
public bool Flag
{
get { return m_flag; }
set
{
m_flag = value;
OnPropertyChanged("Flag");
}
}
private bool m_flag = false;
void Window1_Loaded(object sender, RoutedEventArgs e)
{
this.m_cbox.DataContext = this;
for (int i = 0; i < 1000; i++)
{
Flag = (i % 2 == 0);
Thread.Sleep(200);
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string name)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
void Window1_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
}
#endregion
}
}
Window1.xaml
<Window x:Class="WpfTEST.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" x:Name="window">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.5*" />
<ColumnDefinition Width="0.5*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="0.5*" />
<RowDefinition Height="0.5*" />
</Grid.RowDefinitions>
<CheckBox x:Name="m_cbox" Content="Let's see what happens" Grid.Row="2" Grid.Column="2" Grid.RowSpan="1" Grid.ColumnSpan="1" IsChecked="{Binding Path=Flag, ElementName=window, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
</Grid>
</Window>
The only real problem I see with your code is the sleep loop in Loaded. That causes the UI thread to go unresponsive for the duration of the loop, since you're putting the UI thread into a blocked state.
There's a better way to test if you can change the flag from code and have your binding fire. Add a button to the window, hook up a click handler to the button, and in that click handler, toggle Flag -- I made those modifications to your original code (and removed the sleep loop), clicking on the button toggles the checkbox's state in the fashion you seem to desire.
<Window x:Class="WpfTEST.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" x:Name="window">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.5*" />
<ColumnDefinition Width="0.5*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="0.5*" />
<RowDefinition Height="0.5*" />
</Grid.RowDefinitions>
<!-- I added this button: -->
<Button Click="Button_Click" Grid.Row="0" Grid.Column="0"/>
<CheckBox x:Name="m_cbox" Content="Let's see what happens" Grid.Row="2" Grid.Column="2" Grid.RowSpan="1" Grid.ColumnSpan="1" IsChecked="{Binding Path=Flag, ElementName=window, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
</Grid>
</Window>
and in code behind:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;
namespace WpfTEST {
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window, INotifyPropertyChanged {
public Window1() {
InitializeComponent();
this.Loaded += new RoutedEventHandler(Window1_Loaded);
this.PropertyChanged += new PropertyChangedEventHandler(Window1_PropertyChanged);
}
public bool Flag {
get { return m_flag; }
set {
m_flag = value;
OnPropertyChanged("Flag");
}
}
private bool m_flag = false;
void Window1_Loaded( object sender, RoutedEventArgs e ) {
this.m_cbox.DataContext = this;
Flag = false;
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged( string name ) {
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
void Window1_PropertyChanged( object sender, PropertyChangedEventArgs e ) {
}
#endregion
private void Button_Click( object sender, RoutedEventArgs e ) {
Flag = !Flag;
}
}
}
Other than the above modifications to add the button and its click handler, and remove that sleep loop, I made no modifications to your original code (although you could streamline it a bit).
That will only work if your Flag property is a dependency property. To get this working in the simplest way i can think of i would do the following :
change your binding to be :
IsChecked="{Binding Path=Flag,Mode=TwoWay}"
and in your constructor in your code behind do this :
DataContext = this;
or in XAML
DataContext="{Binding RelativeSource={RelativeSource self}}"
Note : Flag does not need to be a dependency property if you are setting the datacontext to be the window.

Categories