I have a pre-loader screen that essentially says "please wait" as I have server-side computation being processed for several seconds.
I have a value converter that should update and get rid of the loader screen once the server-side computation has been processed and stored.
WPF Portion
<Window.Resources>
<Client:BoolToVisibilityConverter x:Key="loadConverter"/>
</Window.Resources>
.
.
.
<Border Panel.ZIndex="1000" BorderBrush="Yellow" BorderThickness="1" Visibility="{Binding OverlayVisibility, Converter={StaticResource loadConverter}, Mode=TwoWay}" Background="#80000000" Margin="0,0,0,-25.6">
<Grid>
<TextBlock Panel.ZIndex="100" Margin="0" TextWrapping="Wrap" Text="Loading Passive Seismic Nodes..." HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="21" FontWeight="Bold" Foreground="#FFF"/>
<TextBlock Panel.ZIndex="100" Margin="11,136,12,75.2" TextWrapping="Wrap" Text="Please Wait..." HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="14" FontWeight="Bold" Foreground="#FFF"/>
</Grid>
</Border
I have an OverlayVisibility property in this class that is a boolean value to help toggle the preloader screen.
Portion of the Client Class
public void LoadRoles()
{
foreach (var roleName in ChefServer.GetCookbookNames())
{
Cookbooks.Add(new Cookbook() { CookbookName = roleName });
}
//This isn't making the preloader disappear
uiContext.Send((_ => { overlayVisibility = false; }), null);
Console.WriteLine("Done!"); //This gets called successfully
}
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
//This function gets called when WPF form loads
public void Loader()
{
uiContext = SynchronizationContext.Current; //Declared at top in namespace
OverlayVisibility = true; //Make preloader screen show at boot
}
#region Props
private bool overlayVisibility;
public bool OverlayVisibility
{
get { return overlayVisibility; }
set
{
overlayVisibility = value;
OnPropertyChanged("OverlayVisibility");
}
}
#endregion
You're setting overlayVisibility (the field), not OverlayVisibility (the property).
Therefore, you never actually raise PropertyChanged, and WPF never finds out.
Are you sure you have set up DataContext correctly? try adding the following line to your c'tor if you have not set it up yet
this.DataContext = this;
Related
I have a button which only should be active if the given text above it is a valid URL, i got the correct regex and also a OnPropertyChanged method in which i set the button Visibility to true (it gets converted to visibility in the xaml file)...
Although i set the button visibility to true nothing changes
ViewModel Code:
private bool m_isSaveButtonVisible = true;
public bool IsSaveButtonVisible
{
get => m_isSaveButtonVisible;
set
{
m_isSaveButtonVisible = value;
OnPropertyChanged("???"); //i don't know exactly what to call here?
}
}
...
public event PropertyChangedEventHandler PropertyChanged;
protected override void OnPropertyChanged(PropertyChangedEventArgs args)
{
if (MeetingRole == WebRTCMeetingRole.Join)
{
if (Url != m_currentUrl)
{
m_currentUrl = Url;
if (Regex.Match(m_currentUrl, URL_PATTERN, RegexOptions.IgnoreCase).Success)
{
PropertyChanged.Invoke(this, e: args); //should set true
}
else
{
PropertyChanged.Invoke(this, e: args); //should set false
}
}
}
}
XAML Code:
<TextBlock Text="{x:Static p:Resources.webrtc_url}" Foreground="White" FontSize="18" Margin="0 0 0 10"/>
<c:WatermarkTextBox attached:FocusExtension.IsFocused="{Binding IsUrlFocused}"
Foreground="White" FontSize="19" WatermarkForeground="{x:Static co:Colors.Trout}"
Margin="0 0 0 30" Text="{Binding Url, Mode=TwoWay}"
Watermark="{x:Static p:Resources.webrtc_url_hint}" WatermarkHorizontalAlignment="Left" HasFocus="True" SelectAll="True"
EnterCommand="{Binding SaveCommand, Mode=OneTime}" />
...
<c:IconButton Text="{Binding ConfirmButtonText, Mode=OneWay}" TextAlignment="Center" Foreground="White" FontSize="16"
Background="{x:Static co:Colors.DarkOrange}" Margin="0 0 0 8"
Command="{Binding SaveCommand, Mode=OneTime}"
Visibility="{Binding IsSaveButtonVisible, Mode=OneWay, Converter={StaticResource BooleanToVisibilityConverter}}"/>
Does anybody know why the button visibility isn't set ?
What should happen is, when someone writes a valid URL in the Textfield the savebutton should appear
through the OnPropertyChange i already get noticed when somebody writes something in the textfield the problem is that i cant toggle the button out of this function because it doesn't set the visibility and i don't know why
Property changed just notifies WPF that a property has changed. Nothing more.
so:
public event PropertyChangedEventHandler PropertyChanged;
private bool m_isSaveButtonVisible = true;
public bool IsSaveButtonVisible
{
get => m_isSaveButtonVisible;
set
{
m_isSaveButtonVisible = value;
// if somebody listens to PropertyChanged we tell him IsSaveButtonVisible has changed
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IsSaveButtonVisible)));
}
}
Should be enough.
I have a preloader screen user control with dynamic text that is bound to a PreloaderContent property within a singleton class. Singleton, because I want to just have a single instance of this property and change it easily within my application. The class is a singleton so I could easily implement INotifyPropertyChanged into the class to update the UI when the property value changes.
This method of binding below reflects the initial property value. However, whenever I change the property via accessing the singleton instance, the change is not reflected..
<TextBlock Panel.ZIndex="100" Margin="0" TextWrapping="Wrap" Text="{Binding PreloaderContent, Source={x:Static models:Loader.LoaderManager}}" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="21" FontWeight="Bold" Foreground="#FFF">
Preloader Singleton
{
//TO-DO: Make this a singleton class to implement iNotifyPropertyChanged
//TO-DO: Also, potentially move this into a different directory?
public class Loader : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
private static Loader _LoaderManager = new Loader();
public static Loader LoaderManager
{
get { return _LoaderManager; }
}
// Visbility parameter to determine visbility of custom preloader user control
private Visibility _preloader;
public Visibility Preloader
{
get
{
return _preloader;
}
set
{
_preloader = value;
if (_preloader != value)
{
_preloader = value;
NotifyPropertyChanged();
}
}
}
// Textual content showing preloader message inside preloader user control
private string _preloaderContent;
public string PreloaderContent {
get
{
return _preloaderContent;
}
set
{
_preloaderContent = value;
if (_preloaderContent != value)
{
_preloaderContent = value;
NotifyPropertyChanged();
}
}
}
}
}
XAML Code
Now, I want to bind the Text="" to the property of PreloaderContent (Which exists in another class, not the viewmodel), but I am having issues getting it to actually reflect the changes in the UI when the value changes.
<Grid>
<Border Panel.ZIndex="1000" d:IsHidden="True" Background="#80000000" Margin="0,0,0,-0.4">
<Grid>
<TextBlock Panel.ZIndex="100" Margin="0" TextWrapping="Wrap" Text="" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="21" FontWeight="Bold" Foreground="#FFF">
</TextBlock>
<TextBlock Panel.ZIndex="100" Margin="11,136,12,75.2" TextWrapping="Wrap" Text="Please Wait..." HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="14" FontWeight="Bold" Foreground="#FFF"/>
</Grid>
</Border>
Either the other class must also be static, or your Loader class must have a property that the other class can set which is reflected in the text box.
Rookie mistake. I was overriding the preloader value in my Content setter
_preloader = value;
I am new to xaml, WPFs, C# and the MVVM paradigm. I have started with an app based on this example project, in the selected excerpts i want to disable the authenticate button from the LoginPageViewModel after the authenticate button has been clicked(There is no point clicking the button if you are authenticated). I have got command binding working, as well as text control binding between the view and ViewModel. my LoginPageViewModel is based on a abstract class that inherits from INotifyPropertyChanged
The setter AuthenticateButtonEnabled is working, but it is not binding to the isEnabled proprerty on the form. My question is, what could I have missed, and How can i trace the binding between a View and a ViewModel?
the LoginPageView.xaml button:
<Button x:Name="authenticateButton" Content="{x:Static res:Strings.LoginPage_authenticateButton_content}"
Grid.Column="2" Margin="53,4,0,10"
Grid.Row="2" FontSize="16"
IsEnabled="{Binding Path=AuthenticateButtonEnabled}"
Command="{Binding Path=AuthenticateCommand}" HorizontalAlignment="Left" Width="87"/>
the viewModel
private String _username;
private String _responseTextBlock;
private String _linkTextBlockURI;
private String _linkTextBlockText;
private bool _authenticateButtonEnabled;
...
private async void Authenticate()
{
ResponseTextBlock = Strings.LoginPage_responseBlock_content_checking;#this works!
AuthenticateButtonEnabled = false;
return;
}
....
public bool AuthenticateButtonEnabled
{
get { return _authenticateButtonEnabled; }
set { _authenticateButtonEnabled = value; OnPropertyChanged("AuthenticateButtonEnabled"); }
}
// this is in the abstract class.
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = this.PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
If you want to have both: command and AuthenticateButtonEnabled, then simply check for this property in CanExecute delegate and vise-versa in property setter update command.
Here is implementation with DelegateCommand and some improvements which you may find useful:
bool _isAuthenticateButtonEnabled;
public bool IsAuthenticateButtonEnabled
{
get { return _isAuthenticateButtonEnabled; }
set
{
_isAuthenticateButtonEnabled = value;
OnPropertyChanged();
AuthenticateCommand.Update();
}
}
// the base could class could actually implement this
void OnPropertyChanged([CallerMemberName] string property) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property));
public DelegateCommand AuthenticateCommand { get; }
// view model constructor
public ViewModel()
{
AuthenticateCommand = new DelegateCommand(o =>
{
... // some actions when command is executed
}, o =>
{
bool somecondition = ...; // some condition to disable button, e.q. when executing command
return somecondition && IsAuthenticateButtonEnabled;
});
}
This will let you to have both: property to enable/disable button, which can be used in binding (to another control, e.g. CheckBox.IsChecked) and command which can have independent condition to disable button when command shouldn't be executed (typically in async command delegate, when it performs a long running command, but for this you may want to check this answer.).
if you bind the command Property of the Button to an ICommand Property in your Viewmodel, then you do NOT need to handle the IsEnabled Property of the Button because its handled by the CanExecute Method of the ICommand implementation.
google for RelayCommand or DelegateCommand
Thanks to the posters for your help, I wanted to share the working solution for others. I used the DelegateCommand, but had to change some parts in the loginPageViewModel to make it work: I also updated the xaml so that the controls were all inactive after a successful authentication.
the loginPage xaml:
<Label x:Name="usernameLabel" Content="{x:Static res:Strings.LoginPage_usernameLabel_content}" HorizontalAlignment="Left" Margin="10,4,0,0" Grid.Row="0" VerticalAlignment="Top" Width="130" FontSize="16" Height="36" Grid.Column="1"/>
<TextBox x:Name="usernameTextBox" Grid.Column="2" Grid.Row="0" TextWrapping="Wrap"
Text="{Binding Username, UpdateSourceTrigger=PropertyChanged}"
IsEnabled="{Binding AuthenticateButtonEnabled}"
Margin="10,5,0,6" FontSize="16" HorizontalAlignment="Left" Width="130" TextChanged="usernameTextBox_TextChanged"/>
<Label x:Name="passwordLabel" Content="{x:Static res:Strings.LoginPage_passwordLabel_content}" Margin="10,5,0,0" Grid.Row="1" VerticalAlignment="Top" FontSize="16" Height="36" Grid.RowSpan="2" HorizontalAlignment="Left" Width="130" Grid.Column="1"/>
<PasswordBox x:Name="passwordBox" Grid.Column="2" Margin="10,0,0,9"
PasswordChanged="PasswordBox_PasswordChanged"
IsEnabled="{Binding AuthenticateButtonEnabled}"
Grid.Row="1" FontSize="16" HorizontalAlignment="Left" Width="130"/>
<Button x:Name="authenticateButton" Content="{x:Static res:Strings.LoginPage_authenticateButton_content}"
Grid.Column="2" Margin="53,4,0,10"
Grid.Row="2" FontSize="16"
IsEnabled="{Binding AuthenticateButtonEnabled}"
Command="{Binding Path=AuthenticateCommand}" HorizontalAlignment="Left" Width="87"/>
the loginPageViewModel:
....
private bool _authenticateButtonEnabled;
private DelegateCommand _authenticateCommand;
public bool AuthenticateButtonEnabled {
get { return _authenticateButtonEnabled; }
set
{
_authenticateButtonEnabled = value;
DynamicOnPropertyChanged(); // this is so named to not content with onPropertyChanged defined elsewhere.
AuthenticateCommand.Update();
}
}
...
public DelegateCommand AuthenticateCommand
{
get {
if (_authenticateCommand == null)
{
_authenticateCommand = new DelegateCommand(Authenticate, AuthenticateEnded);
}
return _authenticateCommand;
}
}
private bool AuthenticateEnded(object obj) {
return _authenticateButtonEnabled;
}
private async void Authenticate(object obj)
{
AuthenticateButtonEnabled = false;
ResponseTextBlock = Strings.LoginPage_responseBlock_content_checking;
i3SoftHttpClient _httpClient = new i3SoftHttpClient();
i3SoftUser _i3SoftUser;
AuthenticateCommand.CanExecute(false);
....
// if authentication does not succeed - turn the buttons back on.
AuthenticateCommand.CanExecute(true);
}
and to the Delegate command class i added:
public void Update()
{
if (CanExecuteChanged != null)
CanExecuteChanged(this, EventArgs.Empty);
}
I have below code to bind ListBox data using MVVM. I would like to implment the Command from MVVM, data is binded completely and I don't know why it doesn't work with the Command. I don't receive the message when clicking on the button.
ViewModel
public class BookmarkViewModel : INotifyPropertyChanged
{
public BookmarkViewModel()
{
DataSource ds = new DataSource();
deleteBookmark = new Command(executeCommand) { Enabled = true };
_bk = ds.getBookmarkDetail();
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
List<BookmarkDetail> _bk;
public List<BookmarkDetail> Bookmarks
{
get { return _bk; }
set
{
if (_bk != value)
{
_bk = value;
OnPropertyChanged("Bookmarks");
}
}
}
private Command deleteBookmark;
public Command DeleteBookmark
{
get
{
return deleteBookmark;
}
set
{
deleteBookmark = value;
}
}
void executeCommand()
{
System.Windows.MessageBox.Show(_bk[0].SuraName);
}
public class Command : ICommand
{
private readonly Action executeAction;
private bool enabled;
public bool Enabled
{
get
{
return enabled;
}
set
{
if (enabled != value)
{
enabled = value;
if (CanExecuteChanged != null)
CanExecuteChanged(this, new EventArgs());
}
}
}
public Command(Action executeAction)
{
this.executeAction = executeAction;
}
public bool CanExecute(object parameter)
{
return enabled;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
executeAction();
}
}
}
and XAML binding
<ListBox x:Name="lsbBookmarks" FontFamily="./Fonts/ScheherazadeRegOT.ttf#Scheherazade"
FlowDirection="RightToLeft"
Style="{StaticResource ListBoxStyle1}"
ItemsSource="{Binding Bookmarks}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel HorizontalAlignment="Stretch">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"></ColumnDefinition>
<ColumnDefinition Width="60"></ColumnDefinition>
</Grid.ColumnDefinitions>
<StackPanel Orientation="Horizontal" Grid.Column="0"
HorizontalAlignment="Stretch">
<TextBlock Padding="20,0,10,0" HorizontalAlignment="Stretch">
<Run FontSize="50" Text="{Binding ArabicText.ArabicAyaNumber}"
FontFamily="./Fonts/KPGQPC.otf#KFGQPC Uthmanic Script HAFS"
Foreground="Blue"/> <Run FontSize="30" Text="{Binding ArabicText.Aya}"/>
</TextBlock>
</StackPanel>
<Button Grid.Column="1" Tag="{Binding ArabicText.ArabicTextID}"
VerticalAlignment="Center"
Height="60" Width="50" HorizontalAlignment="Right"
Content="X" BorderBrush="Red"
Background="Red" BorderThickness="0"
Padding="0" Command="{Binding DeleteBookmark}"></Button>
</Grid>
<Line X1="0" X2="1" Y1="0" Y2="0" Stretch="Fill" VerticalAlignment="Bottom"
StrokeThickness="1" Stroke="LightGray" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
Any Ideas, How to implement the Command using MVVM?
Thanks!
If I were you I would:
Move the Command implementation to a separate file or declare it outside the scope of the BookmarkViewModel class.
Use the second option as ig2r suggested. Your binding would look like this:Command="{Binding DataContext.DeleteBookmark, ElementName=lsbBookmarks}" You can also use any other ElementName other than lsbBookmarks that's defined as a parent of the ListBox.
It appears that your DeleteBookmark command is exposed as a property on the BookmarkViewModel class, whereas the actual data context within the DataTemplate used to render individual ListBox items will be an instance of BookmarkDetail. Since BookmarkDetail does not declare a DeleteBookmark command, the binding fails.
To correct this, either:
Define and expose the DeleteBookmark command on the BookmarkDetail class, or
Extend your command binding to tell the binding system where to look for the delete command, e.g., Command="{Binding DataContext.DeleteBookmark, ElementName=lsbBookmarks}" (untested).
When the user wants to add a new Reminder, they click the add button on the mainWindow; and once they have added the data, it should display it in a listbox on the main window using an observable collection.
This brings up a new window which brings up options of, at the moment Date and message.
When the user has entered the data, Finish method is called.
The issue is, when the user has finished inputting the data on the new window, I add it to the reminder collection, but it doesn't update on the main window. I am wondering if is a datacontext issue and if I am even going about this the right way?
Thanks for the help.
Add Window:
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class AddWindow : Window, INotifyPropertyChanged
{
private MainWindow mainW;
public AddWindow(MainWindow mW)
{
InitializeComponent();
mainW = mW;
this.Show();
DataContext = this;
}
private void Finish(object sender, RoutedEventArgs e)
{
mainW.Reminders.Add(new Remind(SelectedDate, Message));
this.Close();
}
private DateTime selectedDate = DateTime.Today;
public DateTime SelectedDate
{
get
{
return selectedDate;
}
set
{
if (value != selectedDate)
{
selectedDate = value;
RaisePropertyChange("SelectedDate");
}
}
}
private string message;
public string Message
{
get
{
return message;
}
set
{
if (message != value)
{
message = value;
RaisePropertyChange("Message");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChange(string name)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
}
}
Add Xaml
<TextBox Name="Time" HorizontalAlignment="Left" Height="28" Margin="124,60,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="115"/>
<DatePicker SelectedDate="{Binding SelectedDate}" HorizontalAlignment="Left" Height="28" Margin="124,27,0,0" VerticalAlignment="Top" Width="115"/>
<TextBox Text="{Binding Msg}" HorizontalAlignment="Left" Height="58" Margin="123,93,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="144"/>
<Button Content="Finish" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Margin="135,226,0,0" Click="Finish" />
MainWindow:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = this;
}
private ObservableCollection<Remind> reminders = new ObservableCollection<Remind>();
public ObservableCollection<Remind> Reminders
{
get
{
return reminders;
}
}
private void Add(object sender, RoutedEventArgs e)
{
AddWindow addWindow = new AddWindow(this);
}
}
Mainwindow Xaml:
</MenuItem>
<MenuItem Header="About">
<MenuItem Header="Info"/>
</MenuItem>
</Menu>
<Button Content="New" HorizontalAlignment="Left" Height="26" Margin="6,279,0,0" VerticalAlignment="Top" Width="81" Click="Add" />
<Button Content ="Delete" HorizontalAlignment="Left" Height="26" Margin="87,279,0,0" VerticalAlignment="Top" Width="79" />
<Button Content="Change" HorizontalAlignment="Left" Height="26" Margin="166,279,0,0" VerticalAlignment="Top" Width="73" />
<ScrollViewer Name="Scroller" HorizontalAlignment="Left" Height="235" Margin="0,31,0,0" VerticalAlignment="Top" Width="346">
<ListBox ItemsSource= "{Binding Reminders}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Height="41" Width="293" >
<TextBlock Text="{Binding Path=dateT}"/>
<TextBlock Text="{Binding Path=Msg}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</ScrollViewer>
<Separator HorizontalAlignment="Left" Height="13" Margin="0,266,0,0" VerticalAlignment="Top" Width="362"/>
Remind :
public class Remind : INotifyPropertyChanged
{
public Remind(DateTime dt, string ms)
{
DateT = dt;
Msg = ms;
}
private DateTime datet;
public DateTime DateT
{
get
{
return datet;
}
set
{
if (datet != value)
{
datet = value;
RaisePropertyChange("dateT");
}
}
}
private string msg;
public string Msg
{
get
{
return msg;
}
set
{
if (msg != value)
{
msg = value;
RaisePropertyChange("Msg");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChange(string name)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
}
Change dateT to DateT in your main window
<TextBlock Text="{Binding Path=DateT}"/>
and you are done.
Under the bottom line everthing with the datacontext was ok. Your the 2 wrong property names were missspelled.
Hm, I created a small solution with your code and it just works fine. The main windows's list gets updated right after I click finish. The only small problem is you use the wrong binding in AddWindow to the message. You bind to "Msg" but it should be "Message" in the 3rd line above:
<TextBox Text="{Binding Message}" HorizontalAlignment="Left" Height="58" Margin="123,93,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="144"/>
Code looks fine but I can see one issue in it:
TextBox in AddWindow is binded with Msg but the corresponding property name in code behind is Message. So, textBox is never binded properly and hence new item is added in collection with String.Empty value for Msg.
<TextBox Text="{Binding Msg}" <-- HERE. It should be Message.
However, it should still show a new object in collection on GUI with empty string and DateTime value set on AddWindow even in case of binding failure.
For updated Remind class in question:
One issue in XAML binding where you are binding with field instead of it's wrapper property.
<TextBlock Text="{Binding Path=dateT}"/> <-- HERE, Path name should be DateT.