Binding TextBlock text not update except Initial - caliburn.micro

I'm new on Caliburn.Micro.
The Binding a text on TextBlock.
The text of TextBlock is changed on start up or initialize on ViewModel,
But it would not change in fired function.
I don't know why for a day.
I need any help badly.
Here is code what i wrote.
In View
<TextBlock Grid.Row="0" FontSize="72" Foreground="White"
HorizontalAlignment="Center" VerticalAlignment="Center"
x:Name="DisplayedPhoneNumber"/>
In ViewModel
//! Scren Binding.
public string DisplayedPhoneNumber { get; set; } ="0103214321";
When i press a button on view, i call a function like this,
In View
<Border Style="{StaticResource StyleNumberKeyBorder}">
<Button Content="1" Style="{StaticResource StyleNumberKeyButton}"
cal:Message.Attach="[Event Click]=[Action CmdNumberClick(1)]"/>
</Border>
In ViewModel, CmdNumberClick function like this...
public void CmdNumberClick(string pressed_number)
{
DisplayedPhoneNumber = "plz change...";
}
I check the fired function, and checked DisplayedPhoneNumber is changed,
But TextBlck was not changed.
Please help.

public string DisplayedPhoneNumber { get; set; }
needs to be
private string _displayedPhoneNumber;
public string DisplayedPhoneNumber{
get{ return _displayedPhoneNumber;}
set{
_displayedPhoneNumber = value;
NotifyOfPropertyChanged(() => DisplayedPhoneNumber);
}
}
Associated ViewModel has to inherit PropertyChangedBase or a base class that derives INotifyPropertyChanged;

Related

Is there any way to force a WinUI 3 Datagrid to refresh (re-render) after the bound ItemsSource has changed?

I'm using the CommunityToolkit.WinUI.UI.Controls.DataGrid control.
The ItemsSource property is bound to an ObservableCollection of objects.
These objects have a boolean-type property that I am binding checkboxes to.
The problem:
When a background operation changes the boolean value of some of the objects in the ObservableCollection, the datagrid doesn't reflect the new value (checkbox checked or not checked).
However, if I scroll the datagrid so the affected rows are no longer visible, then scroll back to the affected rows, the value is now rendered correctly.
So there is a work-around -- except for a datagrid that doesn't have enough rows to scroll.
Applicable Code:
<controls:DataGrid Grid.Row="1" AutoGenerateColumns="False" ItemsSource="{Binding UiModel.Dictionary.Values}" CanUserReorderColumns="False" GridLinesVisibility="All" BorderBrush="LightGray" BorderThickness="1" PointerPressed="DataGrid_PointerPressed">
UIModel.Dictionary.Values definition:
IDictionary<string, ObservableCollection<MyClass<T>>>
The IDictionary is assigned an ObservableDictionary as defined at https://learn.microsoft.com/en-us/uwp/api/windows.foundation.collections.iobservablemap-2?view=winrt-22621.
MyClass definition:
using CommunityToolkit.Mvvm.ComponentModel;
public class MyClass<T> : ObservableObject
{
public string Display { get; set; }
public T Identifier { get; set; }
private bool _selected;
public bool Selected
{
get { return _selected; }
set
{
_ = SetProperty(ref _selected, value);
}
}
}
The DataTemplate binding:
<controls:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox Style="{StaticResource CompactCheckbox}" IsChecked="{Binding Path=[0].Selected, Mode=TwoWay}" HorizontalAlignment="Center" MinWidth="0" />
</DataTemplate>
</controls:DataGridTemplateColumn.CellTemplate>
Adding UpdateSourceTrigger=PropertyChanged to the CheckBox binding doesn't help.
Also adding Mode=TwoWay, UpdateSourceTrigger=PropertyChanged to the ItemsSource binding of the DataGrid doesn't help either.
The class in which the Selected property is defined should implement INotifyPropertyChanged and raise the PropertyChanged event in the setter:
private bool _selected;
public bool Selected
{
get { return _selected; }
set { _selected = value; NotifyPropertyChanged(); }
}

How to bind two different class properties in DataTemplate

I am trying to bind two properties from different classes in DataTemplate.
<DataTemplate x:Key="DemoItemTemplate" x:DataType="local:DemoInfo">
<NavigationViewItem Visibility="{Binding Visibility, Mode=TwoWay}" Content="{x:Bind Name}"/>
</DataTemplate>
DataType set as DemoInfo for this DataTemplate and Name value updated from DemoInfo.
I have tried view model as source and relative source binding. But Visibility property binding not working from ViewModel class. Any suggest how to achieve this?
Visibility="{Binding Visibility, Source={StaticResource viewModel}}"
AFAIK , you cant use multibinding in UWP , you can try to use Locator What is a ViewModelLocator and what are its pros/cons compared to DataTemplates?
How to bind two different class properties in DataTemplate
If you bind Visibility with StaticResource, please declare ViewModel class in your page Resources like the following.
ViewModel
public class ViewModel
{
public ViewModel()
{
Visibility = false;
}
public bool Visibility { get; set; }
}
Xaml
<Page.Resources>
<local:ViewModel x:Key="ViewModel" />
</Page.Resources>
<DataTemplate x:DataType="local:Item">
<TextBlock
Width="100"
Height="44"
Text="{x:Bind Name}"
Visibility="{Binding Visibility, Source={StaticResource ViewModel}}" />
</StackPanel>
</DataTemplate>
Update
If you want Visibility value changed dynamically at run-time, you need implement INotifyPropertyChanged interface for ViewModel class.
public class ViewModel : INotifyPropertyChanged
{
public ViewModel()
{
Visibility = false;
}
private bool _visibility;
public bool Visibility
{
get
{
return _visibility;
}
set
{
_visibility = value;
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string PropertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(PropertyName));
}
}
For more detail please refer Data binding in depth official document.

Binding two viewModel to one view

i am trying to bind my MasterViewModel where i have initiated two original viewModel to one view. But i am not getting any data so i must be doing the binding wrong. I have found several post
I have tried
in Xaml
<Label
x:Name="SectionRequired"
Grid.Row="2"
HorizontalOptions="End"
IsVisible="{Binding PostViewModel.IsRequired, Source={x:Reference PostViewModel}}"
Text="{x:Static resources:AppResources.AlertRequired}"
TextColor="Red" />
And also followed this solution but i was getting an expcetion that its used lika markup extenstion 'local1:PostViewModel' is used like a markup extension but does not derive from MarkupExtension.
https://stackoverflow.com/questions/50307356/multiple-bindingcontexts-on-same-contentpage-two-different-views
My Master
class MasterPostsViewModel : BaseViewModel
{
public PostViewModel postViewModel { get; set; }
public CategoriesViewModel categoriesViewModel { get; set; }
public MasterPostsViewModel()
{
postViewModel = new PostViewModel();
categoriesViewModel = new CategoriesViewModel();
}
}
}
Conte page
I have set the binding to one field here and that works, buit having to do that for the whole page is not what i want.
MasterPostsViewModel ViewModel;
protected override void OnAppearing()
{
base.OnAppearing();
BindingContext = ViewModel = new MasterPostsViewModel();
NameRequired.IsVisible = ViewModel.postViewModel.IsRequired;
}
Can you help please
instead of
IsVisible="{Binding PostViewModel.IsRequired, Source={x:Reference PostViewModel}}"
just use
IsVisible="{Binding postViewModel.IsRequired}"
your property name is postViewModel is lower case
also, get rid of this line - it will break the binding you have setup in the XAML
NameRequired.IsVisible = ViewModel.postViewModel.IsRequired;

xamarin forms unable to show sqlite data in listview

I am struggling to find the answer by myself, using previous Stackoverflow posts, youtube and google searching.
I am trying to learn how to use SQLite with xamarin forms.
Solution connection:
using SQLite;
namespace TestSQLite
{
public interface IDatabaseConnection
{
SQLiteAsyncConnection GetConnection();
}
}
Android specific connection (iOS is identical)
using SQLite;
using System.IO;
using TestSQLite;
using Xamarin.Forms;
[assembly: Dependency(typeof(DatabaseConnection))]
namespace TestSQLite
{
public class DatabaseConnection : IDatabaseConnection
{
public SQLiteAsyncConnection GetConnection()
{
var dbName = "TestDb.db3";
var path = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments), dbName);
return new SQLiteAsyncConnection(path);
}
}
}
And the MainPage C# code:
using SQLite;
using Xamarin.Forms;
namespace TestSQLite
{
public class ControlledDrugs
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public string Drug { get; set; }
public double Volume { get; set; }
}
public class Users
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public string Name { get; set; }
}
public partial class MainPage : ContentPage
{
private SQLiteAsyncConnection _connection;
public MainPage()
{
InitializeComponent();
_connection = DependencyService.Get<IDatabaseConnection>().GetConnection();
}
protected override async void OnAppearing()
{
await _connection.CreateTableAsync<ControlledDrugs>();
await _connection.CreateTableAsync<Users>();
RefreshUsers();
RefreshDrugs();
base.OnAppearing();
}
async void OnAdd(object sender, System.EventArgs e)
{
var user = new Users { Name = UserInput.Text };
await _connection.InsertAsync(user);
}
void OnUpdate(object sender, System.EventArgs e)
{
}
void OnDelete(object sender, System.EventArgs e)
{
}
async void RefreshUsers()
{
var userlist = await _connection.Table<Users>().ToListAsync();
Userlistview.ItemsSource = userlist;
}
async void RefreshDrugs()
{
var druglist = await _connection.Table<ControlledDrugs>().ToListAsync();
Drugslistview.ItemsSource = druglist;
}
private void Userlistview_Refreshing(object sender, System.EventArgs e)
{
RefreshUsers();
Userlistview.EndRefresh();
}
}
}
I know the add to sqlite method works, firstly because a user on Stackoverflow helped me, and secondly a blank cell appears on the listview. But thats the issue, the cells are blank, no matter how many I add, all blank.
I can't seem to physically access the sqlite database on the emulator to open and investigate if the entries are being written or entered as blanks. System.Environment.SpecialFolder.MyDocuments does not seem to save the .db3 in the emulator My Documents - separate issue, but limiting me to find the answer myself.
So i know the issue is either: 1)when the solution enters the data into the database (as blank) or if 2)the recall of data from the database to be viewed on the listview has the error.
Also, from my code you can probably see I am calling the refresh listview manually (by the user pulling the listview, because I am still learning and observable collection method/approach is a bit beyond me ATM.
Thanks team
UPDATE: Xaml code as requested: Thank you.
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:TestSQLite"
x:Class="TestSQLite.MainPage">
<StackLayout>
<Label Text="User Input"></Label>
<Entry x:Name="UserInput"></Entry>
<Button Text="add it" Clicked="OnAdd"></Button>
<Label Text="User"></Label>
<ListView x:Name="Userlistview" IsPullToRefreshEnabled="True" Refreshing="Userlistview_Refreshing"></ListView>
<Label Text="Drugs"></Label>
<ListView x:Name="Drugslistview"></ListView>
</StackLayout>
</ContentPage>
I'm a bit late, but hopefully this will help someone in the future (it would have certainly helped me!)
I ran into this same problem while working through the Xamarin tutorials on Microsoft's site. The tutorial first had you save a list to files, then changed to using the SQLite database. When I switched I found that adding a new record populated a blank list entry.
The culprit turned out to be in the binding between the data entry page, the list view and the variable names in the class. I had the class defined as:
public class Player
{
[PrimaryKey, AutoIncrement]
public int ID { get; set; }
public string PlayerName { get; set; }
public DateTime JoinDate { get; set; }
}
When performing data entry I SHOULD have had:
<StackLayout Margin="20">
<Editor Placeholder="Enter player name"
Text="{Binding PlayerName}"
HeightRequest="50" />
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Button Text="Save"
Clicked="OnRosterEntrySaveButtonClicked"
Grid.Row="1" />
<Button Text="Delete"
Clicked="OnRosterEntryDeleteButtonClicked"
Grid.Row="1"
Grid.Column="1"/>
</Grid>
</StackLayout>
Instead I had "Text = "{Binding Text}" in the Editor. This didn't generate an error on build. I also had an error in the list view. What I SHOULD have had was:
<ListView.ItemTemplate>
<DataTemplate>
<TextCell Text="{Binding PlayerName}"
Detail="{Binding Date}" />
</DataTemplate>
</ListView.ItemTemplate>
Instead I again had "Text" instead of "PlayerName". Note above that "Detail="{Binding Date}" is also wrong. The variable in the class is actually JoinDate. The above binding doesn't generate an error, however when the app runs no data is shown. Changing the binding to JoinDate and re-building allows the data to be shown.
My recommendation would be to check your bindings for setting and displaying the data on those pages.

WPF - How to bind to a Dependency Property of custom class

I'm once again in WPF binding hell :) I have a public class (Treatment) as follows:
public class Treatment()
{
...
public Ticker SoakTimeActual;
...
}
Within Ticker is a Dependency Property:
public class Ticker : FrameworkElement
{
// Value as string
public static readonly DependencyProperty DisplayIntervalProperty = DependencyProperty.Register("DisplayInterval", typeof(string), typeof(Ticker), null);
public string DisplayInterval
{
get { return (string)GetValue(DisplayIntervalProperty); }
set { SetValue(DisplayIntervalProperty, value); }
}
...
}
In my app, a single Treatment object is created and is meant to be easily accessible in XAML (in app.xaml ):
<Application.Resources>
<ResourceDictionary>
<u:Treatment
x:Key="currentTreatment" />
</ResourceDictionary>
</Application.Resources>
Now, I need to bind to the DisplayInterval dependency property of SoakTimeActual to display this text in its current state. Here is my attempt, which doesn't work:
<TextBlock
Text="{Binding Source={StaticResource currentTreatment}, Path=SoakTimeActual.DisplayInterval}"/>
This, of course, compiles ok, but will not display anything. I'm assuming I've made a mistake with change notification or DataContext or both.
Any insight is appreciated!
WPF binding only operates on properties, not fields.
Therefore, you need change your SoakTimeActual field to a property, like this:
public class Treatment
{
...
public Ticker SoakTimeActual { get; set; }
...
}

Resources