Normal view
- WPF button animation on command finishedI have a listView of items in my app, each item has some configuration and save button. MainWindow: <Grid> <ListView ItemsSource="{Binding ItemVmList}" SelectedItem="{Binding SelectedItem}" Padding="0"> <ListView.ItemTemplate> <DataTemplate DataType="{x:Type local:ItemViewModel}"> <local:ItemView /> </DataTemplate> </ListView.ItemTemplate> </ListView> </G
WPF button animation on command finished
I have a listView of items in my app, each item has some configuration and save button. MainWindow:
<Grid>
<ListView ItemsSource="{Binding ItemVmList}"
SelectedItem="{Binding SelectedItem}"
Padding="0">
<ListView.ItemTemplate>
<DataTemplate DataType="{x:Type local:ItemViewModel}">
<local:ItemView />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
MainVM:
public class MainViewModel : ViewModelBase
{
private readonly IItemProvider _itemProvider;
private readonly ISettingsManager _settingsManager;
private ItemViewModel _selectedItem;
public ObservableCollection<ItemViewModel> ItemVmList { get; set; }
public ItemViewModel SelectedItem
{
get => _selectedItem;
set
{
_selectedItem = value;
OnPropertyChanged(nameof(SelectedItem));
}
}
public MainViewModel(IItemProvider itemProvider, ISettingsManager settingsManager)
{
_itemProvider = itemProvider;
_settingsManager = settingsManager;
var itemList = _itemProvider.GetItems();
ItemVmList = new ObservableCollection<ItemViewModel>(
itemList.Select(x => new ItemViewModel(settingsManager, x)));
SelectedItem = ItemVmList.First();
}
}
ItemView:
<Grid Height="50"
Width="500">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="400" />
<ColumnDefinition Width="50" />
<ColumnDefinition Width="50" />
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Name, Mode=OneWay}"
FontSize="18"
Grid.Column="0"
HorizontalAlignment="Center"
Height="50" />
<TextBox Grid.Column="1"
FontSize="18"
Width="50"
Height="50"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Text="{Binding Value, Mode=TwoWay}" />
<Button Width="50"
Height="50"
Grid.Column="2">
Save
</Button>
</Grid>
ItemVM:
public class ItemViewModel : ViewModelBase
{
private readonly ISettingsManager _settingsManager;
private readonly ItemModel _item;
public string Name
{
get { return _item.Name; }
}
public int Value
{
get { return _item.Value; }
set
{
_item.Value = value;
OnPropertyChanged(nameof(Value));
}
}
public ItemViewModel(ISettingsManager settingsManager, ItemModel item)
{
_settingsManager = settingsManager;
_item = item;
}
}
ISettingsManager have here only Save() method.
I want my save button to change style or play animation based on the result of the Save method (if true - green color and red if false). Also it would be good to move command logic from ItemVM if possible. I tried that with command, but I didn't find any way to somehow bind button style to Save() result.
- How can I retrieve the current duration from the Media Player to display on the song progress bar?i have tried every possible step but only giving value once, i want it should update every single second. this is my code, where i'm doing wrong? i want to impliment progress slider for musics, any one please can help me? here I'm using a slider library which you this library accept range from current position to total duration. data class MusicPlayerStates( var playingSongCurrentPosition: MutableState<Int> = mutableIntStateOf(0), var playingSongDuration: MutableState<Int> =
How can I retrieve the current duration from the Media Player to display on the song progress bar?
i have tried every possible step but only giving value once, i want it should update every single second. this is my code, where i'm doing wrong?
i want to impliment progress slider for musics, any one please can help me?
here I'm using a slider library which you this library accept range from current position to total duration.
data class MusicPlayerStates(
var playingSongCurrentPosition: MutableState<Int> = mutableIntStateOf(0),
var playingSongDuration: MutableState<Int> = mutableIntStateOf(0),
//other code
)
fun onEvent(event: MusicPlayerUiEvents) {
when (event) {
is MusicPlayerUiEvents.PlaySong -> {
mediaPlayer?.let {
if (it.isPlaying) {
mediaPlayer?.stop()
mediaPlayer?.reset()
_musicPlayerState.update { state ->
state.copy(
playingSongCurrentPosition = state.playingSongCurrentPosition.apply {
this.value = 0
},
playingSongDuration = state.playingSongDuration.apply {
this.value = 0
}
)
}
}
}
_musicPlayerState.update {
it.copy(
isSongPlaying = it.isSongPlaying.apply {
this.value = true
}
)
}
mediaPlayer?.release()
mediaPlayer = MediaPlayer().apply {
setDataSource(event.url)
prepareAsync()
}
mediaPlayer?.setOnPreparedListener { mediaPlayer ->
mediaPlayer.seekTo(state.value.playingSongCurrentPosition.value)
mediaPlayer.start()
setSongDuration(mediaPlayer.duration)
updatePlaybackState(mediaPlayer.currentPosition)
Log.d("check for currentD_VM","${state.value.playingSongCurrentPosition.value}")
}
mediaPlayer?.setOnCompletionListener { mediaPlayer ->
// Use for precise updates
mediaPlayer?.stop()
_musicPlayerState.update { state ->
state.copy(
playingSongCurrentPosition = state.playingSongCurrentPosition.apply {
this.value = 0
},
playingSongDuration = state.playingSongDuration.apply {
this.value = 0
},
isSongPlaying = state.isSongPlaying.apply {
this.value = false
},
)
}
}
}
}
}
}
private fun updatePlaybackState(currentPosition: Int) {
_musicPlayerState.update {
it.copy(
playingSongCurrentPosition = it.playingSongCurrentPosition.apply {
this.value = currentPosition
}
)
}
}
private fun setSongDuration(duration: Int) {
_musicPlayerState.update {
it.copy(
playingSongDuration = it.playingSongDuration.apply {
this.value = duration
}
)
}
}
Box(
modifier =
Modifier
.padding(vertical = 80.dp, horizontal = 20.dp)
.fillMaxWidth()
.height(20.dp)
) {
var fraction by remember { mutableFloatStateOf(1f) }
WavySlider(
valueRange = 1000f..state.playingSongDuration.value.toFloat(),
value = 1000f,
onValueChange = { },
waveLength = 25.dp, // Set this to 0.dp to get a regular Slider
waveHeight = 10.dp, // Set this to 0.dp to get a regular Slider
waveVelocity = 15.dp to WaveDirection.HEAD, // Speed per second and its direction
waveThickness = 4.dp, // Defaults to the specified trackThickness
trackThickness = 4.dp, // Defaults to 4.dp, same as regular Slider
incremental = false, // Whether to gradually increase waveHeight
// animationSpecs = ... // Customize various animations of the wave
)
}
- maui: navigate to another view from inside a view after a button click in mvvmI am trying to open a new page from another viewmodel. I am doing this: My pages are registered: builder.Services.AddSingleton<SettingsPageView, SettingsPageViewModel>(); builder.Services.AddSingleton<WifiPageView, WifiPageViewModel>(); In my SetttingsPageView i do this: <Button TextColor="Black" Command="{Binding ClickedWifiMenuCommand}" Text="WIFI Menu"/> And the command like this: [RelayCommand] public async void ClickedWifiMenu() { Navigation.PushAsync(new Wi
maui: navigate to another view from inside a view after a button click in mvvm
I am trying to open a new page from another viewmodel. I am doing this:
My pages are registered:
builder.Services.AddSingleton<SettingsPageView, SettingsPageViewModel>();
builder.Services.AddSingleton<WifiPageView, WifiPageViewModel>();
In my SetttingsPageView i do this:
<Button TextColor="Black" Command="{Binding ClickedWifiMenuCommand}" Text="WIFI Menu"/>
And the command like this:
[RelayCommand]
public async void ClickedWifiMenu()
{
Navigation.PushAsync(new WifiPageView());
}
But this is not working.
my Wifipage:
public partial class WifiPageViewModel: ObservableObject
{
private readonly ILocalizationResourceManager _loc;
private readonly ILogger _logger;
public WifiPageViewModel(ILocalizationResourceManager loc, ILogger logger)
{
_loc = loc;
_logger = logger.ForContext<WifiPageViewModel>();
}
code behind:
public WifiPageView(WifiPageViewModel vm)
{
InitializeComponent();
BindingContext = vm;
}
and my empty view:
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
...
x:DataType="ViewModels:WifiPageViewModel">
<StackLayout>
<Label Text="Hi mom"/>
</StackLayout>
</ContentPage>
How can I open my view from my one view?
- Column Series With different color on a different interval at x-axis fill in same series?I'm trying to implement a speed/time plot UI, i'm using WPF with the MVVM Pattern and Live-Charts by beto-rodriguez as my plot library. I am using Column Series. i have two issues: 1) i have to start the series in middle of the x-axis how to do this? e.g if i set the min value as 7 the graph starts the x axis as 7 taking it the first point but i want x - axis to start at 1 but graph plotting should start at 7. 2) i have to change the color of the series at a certain condition say when x= 10 i
Column Series With different color on a different interval at x-axis fill in same series?
I'm trying to implement a speed/time plot UI, i'm using WPF with the MVVM Pattern and Live-Charts by beto-rodriguez as my plot library. I am using Column Series.
i have two issues: 1) i have to start the series in middle of the x-axis how to do this? e.g if i set the min value as 7 the graph starts the x axis as 7 taking it the first point but i want x - axis to start at 1 but graph plotting should start at 7.
2) i have to change the color of the series at a certain condition say when x= 10 i want it to be shown as blue but when x= 17 i want to show the same series as pink only for that value rest at all points it should be of the original color.
Any Pointers?
- How to make changes from ObservableObject derived class reflect into interface automatically?I am using ObservableObject from CommunityToolkit in a WPF program. It looks like this: It's like a ViewModel, I think: public class MyParameters: ObservableObject { // many other values are here public double ValAngleDegrees { get; set;} } A control looks like this: <StackPanel x:Name="AnglePanel" Orientation="Horizontal" Grid.Column="0" Grid.Row="2" Grid.ColumnSpan="2"> <TextBox Name="TxtAngleDeg" Width="100" Margin="2" Text="{Binding Path=ValAngleDegrees, Mode=TwoWay, Upd
How to make changes from ObservableObject derived class reflect into interface automatically?
I am using ObservableObject from CommunityToolkit in a WPF program. It looks like this:
It's like a ViewModel, I think:
public class MyParameters: ObservableObject
{
// many other values are here
public double ValAngleDegrees { get; set;}
}
A control looks like this:
<StackPanel x:Name="AnglePanel" Orientation="Horizontal" Grid.Column="0" Grid.Row="2" Grid.ColumnSpan="2">
<TextBox Name="TxtAngleDeg" Width="100" Margin="2" Text="{Binding Path=ValAngleDegrees, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, NotifyOnSourceUpdated=True}" KeyUp="TxtAngleDeg_KeyUp"></TextBox>
</StackPanel>
I initialize it like this:
public MyParameters renderValues { get; set; }
public MainWindow()
{
InitializeComponent();
renderValues = new MyParameters { ValAngleDegrees = 0 };
AnglePanel.DataContext = renderValues;
}
When I change value in textbox, value in ObservableObject is changed like expected, BUT THE PROBLEM IS - when I change value in code it does not get changed in UI. How do I solve this?
- How to update parent items when delete item on the details page?I have a CollectionView with items when I tap on one, should be redirected to details page with a delete or update button. When I do the operation how should I refresh the parent collectionview? ViewModel of the CollectionviewPage: public class TestViewModel : BaseViewModel { public ObservableCollection<TestItem> TestItems { get; set; } public TestViewModel() { TestItems = new ObservableCollection<TestItem> { new TestItem { Id = 1, Tit
How to update parent items when delete item on the details page?
I have a CollectionView with items when I tap on one, should be redirected to details page with a delete or update button. When I do the operation how should I refresh the parent collectionview?
ViewModel of the CollectionviewPage:
public class TestViewModel : BaseViewModel
{
public ObservableCollection<TestItem> TestItems { get; set; }
public TestViewModel()
{
TestItems = new ObservableCollection<TestItem>
{
new TestItem { Id = 1, Title = "Test Item 1" },
new TestItem { Id = 2, Title = "Test Item 2" },
new TestItem { Id = 3, Title = "Test Item 3" }
};
ItemSelectedCommand = new Command(OnItemSelected);
}
[RelayCommand]
private void OnItemSelected(TestItem selectedItem)
{
await Shell.Current.Navigation.PushAsync(new DetailsPage(selectedItem));
}
}
ViewModel of the DetailsPage:
public class DetailsPageModel : BaseViewModel
{
TestItem _item;
public TestViewModel(TestItem item)
{
_item = item;
}
[RelayCommand]
private async void Delete()
{
// Mock Delete from db
await _repository.Delete(_item);
await Shell.Current.Navigation.PopAsync();
}
}
So in this case I remove the item from database, but how should I notify from details page the parent that it should update? Shall I pass the whole list to the details page and remove from there, does not seem effective?
- Share record to community based on conditionI have two object Schedule and Schedule Item which is in master-detail relationship.I want to show schedule item data on community site based on schedule item account field is match with site login user account if this is full fill these records only show on community site. how can i do this? i am expecting schedule item list which has account same as currunt site login user account.
Share record to community based on condition
I have two object Schedule and Schedule Item which is in master-detail relationship.I want to show schedule item data on community site based on schedule item account field is match with site login user account if this is full fill these records only show on community site. how can i do this?
i am expecting schedule item list which has account same as currunt site login user account.
ChatGPT API in C# WPF / XAML / MVVM
- Angular Signals Ported to .NET and C#Description of a library that allows to use a porting of Angular Signals in .NET MVVM Frameworks
Angular Signals Ported to .NET and C#
- How to bind values of comboboxes of a list view that include them in wpf mvvm view modelI have 2 class: public class Order : ObservableCollection<string> { public Order() { Add("1st"); Add("2nd"); Add("3rd"); for (int i=4; i< 100; i++) { Add($"{i}th"); } } } public class Id : ObservableCollection<string> { public Id() { Add("abc12345"); Add("dce12345"); //3000 id,... } } In my xaml: <DockPanel Grid.Row="2" Grid.Column="0" Height="Auto" Backg
How to bind values of comboboxes of a list view that include them in wpf mvvm view model
I have 2 class:
public class Order : ObservableCollection<string>
{
public Order()
{
Add("1st");
Add("2nd");
Add("3rd");
for (int i=4; i< 100; i++)
{
Add($"{i}th");
}
}
}
public class Id : ObservableCollection<string>
{
public Id()
{
Add("abc12345");
Add("dce12345");
//3000 id,...
}
}
In my xaml:
<DockPanel Grid.Row="2" Grid.Column="0" Height="Auto" Background="LightBlue">
<DockPanel.Resources>
<src:Order x:Key="order"/>
<src:Id x:Key="id"/>
</DockPanel.Resources>
<ListView ItemsSource="{StaticResource order}">
<ListView.View>
<GridView>
<GridViewColumn Header="Order"/>
<GridViewColumn Header="ID">
<GridViewColumn.CellTemplate>
<DataTemplate>
<ComboBox
Width="200"
ItemsSource="{StaticResource id}">
</ComboBox>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
</DockPanel>
It binded just fine: each row in 100 rows of column "Order" (1st to 99th) in the list box got one combobox that can select the ID. But, how i get each combobox selected value in each row, and bind them to a value (or list) which is created in public partial class MainWindowViewModel : ObservableObject
instead of MainWindow
?
I think LINQ is possible but must call from MainWindow
not MainViewModel
. But thats meaningless for my control. Any help is appreaciated.
- Correct Structure for a MVVM WinUI 3 Project?I recently moved over from Windows Forms to XAML and have been trying to make a basic WinUI 3 app. I am wondering what is the correct structure to use for an MVVM WinUI 3 project that connects to a SQL Lite database? I currently have the following although I feel that the two classes I am currently using to talk with the database base (ClientData, OrderData) are wrong. I am using the MVMM Community Toolkit. For the SQL Lite database I have created it using FrameWork Core and migrations. With the
Correct Structure for a MVVM WinUI 3 Project?
I recently moved over from Windows Forms to XAML and have been trying to make a basic WinUI 3 app. I am wondering what is the correct structure to use for an MVVM WinUI 3 project that connects to a SQL Lite database?
I currently have the following although I feel that the two classes I am currently using to talk with the database base (ClientData, OrderData) are wrong. I am using the MVMM Community Toolkit. For the SQL Lite database I have created it using FrameWork Core and migrations.
With the code I have a List View which I want to keep updated whenever something is added/removed from the database.
Database Stuff:
public class DataContext : DbContext
{
public DbSet<Client> Clients { get; set; }
public DbSet<Order> Orders { get; set; }
}
public static class ClientData
{
public static void AddClientData(Client client)
{
using (var db = new CaseNoteManagerContext())
{
db.Add(client);
db.SaveChanges();
}
}
public static List<Client> GetClients()
{
using (var db = new DataContext())
{
return db.Clients.ToList();
}
}
}
public static class OrderData
{
public static void AddOrderData(Order order)
{
using (var db = new DataContext())
{
db.Add(order);
db.SaveChanges();
}
}
}
Models:
public class Order
{
public int Id { get; set; }
public float Amount { get; set; }
public DateTime Date { get; set; }
public Client Client {get; set;}
}
public class Client
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
View Models:
public class ViewModelBase : ObservableObject {}
public partial class ClientViewModel : ViewModelBase
{
public ObservableCollection<Client> Clients { get; set; }
public ClientViewModel() {}
}
public partial class OrderViewModel: ViewModelBase
{
public ObservableCollection<Order> Orders { get; set; }
public OrderViewModel() {}
}
MainWindow.xaml:
<StackPanel x:Name="selectClientsPanel" HorizontalAlignment="Center">
<ListView x:Name="clientsList" BorderThickness="1" Width="350" Height="Auto" HorizontalAlignment="Left"
ItemsSource="{Binding Path=Clients, Mode=TwoWay}">
<ListView.ItemTemplate>
<DataTemplate x:DataType= "model:Client">
<TextBlock Text="{x:Bind FirstName}" x:Phase="1" Margin="0,5,0,5"/>
<TextBlock Text="{x:Bind LastName}" x:Phase="1" Margin="0,5,0,5"/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<StackPanel Margin="30">
<TextBox x:Name="firstNameBox" Header="Enter first name:" PlaceholderText="First Name" />
<TextBox Name="lastNameBoxBox" Width="250" Margin="0,0,8,0"
Header="Enter last name:" PlaceholderText="Last Name"/>
<Button x:Name="createClientBtn" Click="createClientBtn_Click">Create Client</Button>
</StackPanel>
</StackPanel>
MainWindow.xaml.cs:
public sealed partial class MainWindow : Window
{
public ClientViewModel ViewModel { get; }
public MainWindow()
{
this.InitializeComponent();
ViewModel = App.GetService<ClientViewModel>();
clientsList.ItemsSource = ViewModel.Clients;
}
private void createClientBtn_Click(Object sender, RoutedEventArgs e)
{
if (firstNameBox.Text.Length > 0 && lastNameBox.Text.Length)
{
Client client=new User(firstNameBox.Text, lastNameBox.Text);
ViewModel.Clients.Add(client);
ClientData.AddClientData(client);
}
}
}
- Search functionality with retrofit and mvvm androidI have an android application which I use MVVM and Retrofit in. and I want to apply search in this application I have an api for search and api return result correctly via post man but when I try to build it in android I get confused because I get wrong results. this is my code SearchRepo.java public class SearchRepo { private Application application; private ApiService apiService; public SearchRepo(Application application) { this.application = application; this.api
Search functionality with retrofit and mvvm android
I have an android application which I use MVVM and Retrofit in.
and I want to apply search in this application I have an api for search and api return result correctly via post man but when I try to build it in android I get confused because I get wrong results.
this is my code
SearchRepo.java
public class SearchRepo {
private Application application;
private ApiService apiService;
public SearchRepo(Application application) {
this.application = application;
this.apiService = RetrofitClient.getClient(BASE_URL)
.create(ApiService.class);
}
public void SearchForKeyWord(String lang, String keyword, int perPage,
SearchRepositoryCallBack<ProductModel> callBack) {
apiService.search(lang,keyword,perPage)
.enqueue(new Callback<ProductModel>() {
@Override
public void onResponse(Call<ProductModel> call, Response<ProductModel> response) {
if (response.isSuccessful()) {
callBack.onSuccess(response.body());
} else {
callBack.onFailure("Error : "+response.code());
}
}
@Override
public void onFailure(Call<ProductModel> call, Throwable t) {
callBack.onFailure("Error : "+t.getMessage());
}
});
}
public interface SearchRepositoryCallBack<T> {
void onSuccess(T post);
void onFailure(String error);
}
}
SearchViewModel.java
public class SearchViewModel extends AndroidViewModel {
private SearchRepo search;
private MutableLiveData<ProductModel> searchResult = new MutableLiveData<>();
public SearchViewModel(@NonNull Application application) {
super(application);
this.search = new SearchRepo(application);
}
public void searchProducts(String lang,String keyword,int perPage) {
search.SearchForKeyWord(lang, keyword, perPage, new SearchRepo.SearchRepositoryCallBack<ProductModel>() {
@Override
public void onSuccess(ProductModel post) {
searchResult.postValue(post);
}
@Override
public void onFailure(String error) {
Log.e(APITAG,error);
}
});
}
public LiveData<ProductModel> getSearchResult() {
return searchResult;
}
}
search method in searchFragment.java
private void search(String lang, String keyword, int perPage) {
productViewModel.searchProduct(lang,keyword,perPage);
productViewModel.getResultList().observe(getViewLifecycleOwner(), new Observer<ProductModel>() {
@Override
public void onChanged(ProductModel productModel) {
List<Product> mlist = productModel.getData();
for (int i=0;i<mlist.size();i++) {
System.out.println(i);
System.out.println("My List "+mlist.size());
System.out.println("My List "+mlist.get(i).getName());
}
System.out.println("=====================================");
}
});
}
when I type a text to search I get a correct result, but if I removed the word and try to write another one I get old result and correct result, number of result is exponential.
example
1
======
input -> m
expected -> "moon" , "mine"
actual output -> "moon" , "mine"
=====================
2
======
input -> a
expected -> "apple" , "alpha"
actual output -> "moon" , "mine" , "apple" , "alpha" , "apple" , "alpha"
====================
3
======
input -> l
expected -> "locus" , "lord"
actual output -> "apple" , "alpha" , "apple" , "alpha" , "locus" , "lord" , "locus" , "lord"
so what is the problem and how to fix it
- How to get Context in Android MVVM ViewModelI am trying to implement MVVM pattern in my android app. I have read that ViewModels should contain no android specific code (to make testing easier), however I need to use context for various things (getting resources from xml, initializing preferences, etc). What is the best way to do this? I saw that AndroidViewModel has a reference to the application context, however that contains android specific code so I'm not sure if that should be in the ViewModel. Also those tie into the Activity life
How to get Context in Android MVVM ViewModel
I am trying to implement MVVM pattern in my android app. I have read that ViewModels should contain no android specific code (to make testing easier), however I need to use context for various things (getting resources from xml, initializing preferences, etc). What is the best way to do this? I saw that AndroidViewModel
has a reference to the application context, however that contains android specific code so I'm not sure if that should be in the ViewModel. Also those tie into the Activity lifecycle events, but I am using dagger to manage the scope of components so I'm not sure how that would affect it. I am new to the MVVM pattern and Dagger so any help is appreciated!
- Blazing.Mvvm - Blazor Server, WebAssembly, & Hybrid using Mvvm Community ToolkitMVVM made simple via Blazing.Mvvm Library using the Microsoft Community Toolkit
Blazing.Mvvm - Blazor Server, WebAssembly, & Hybrid using Mvvm Community Toolkit
- How to create singleton object and using for UI and viewmodel for two screen in kotlin jetpack compose?I have a list like this data class SelectedNtrItem( val items:ArrayList<NutritionSearchItem> = arrayListOf() ) I need to use this list on two composable screens, so I need to access a single example of it. My idea is to create it with singelton and use it on the UI and Viewmodel side, but I could not do this completely. class SelectedNtrItemManager { companion object{ private val _selectedNtrItem = MutableStateFlow(SelectedNtrItem()) val selectedNtrItem: S
How to create singleton object and using for UI and viewmodel for two screen in kotlin jetpack compose?
I have a list like this
data class SelectedNtrItem(
val items:ArrayList<NutritionSearchItem> = arrayListOf()
)
I need to use this list on two composable screens, so I need to access a single example of it. My idea is to create it with singelton and use it on the UI and Viewmodel side, but I could not do this completely.
class SelectedNtrItemManager {
companion object{
private val _selectedNtrItem = MutableStateFlow(SelectedNtrItem())
val selectedNtrItem: StateFlow<SelectedNtrItem> = _selectedNtrItem.asStateFlow()
}
}
This is the class I created as singelton. How can I use this in the viewmodel and UI side of two composable screens, that is, how can I access this list on both the UI side and the viewmodel side on two screens as a single object because I need the same list?
@Composable
fun FirstScreen(
navHostController: NavHostController,
viewModel: FirstScreenViewModel = hiltViewModel()
) {
...
@HiltViewModel
class FirstScreenViewModel @Inject constructor(
.... ) : ViewModel() { ....
@Composable
fun SecondScreen(
navHostController: NavHostController,
viewModel: SecondScreenViewModel = hiltViewModel()
) {
...
@HiltViewModel
class SecondScreenViewModel @Inject constructor(
.... ) : ViewModel() { ....
- Entry Control: how to work with auto-generated MVVM methodsBasic question, but I can't find the answer in the docs for the Entry control. CommunityToolkit.MvvV comes with these awesome auto-generated methods. Here is one that I want to use with the Entry control:partial void OnNameChanged(string? value) Or:partial void OnNameChanging(string? value) The problem is that it works... too well. When I set up either one of the above methods to work with an Entry control, the method is called as soon as a single character is typed into the control's user-inp
Entry Control: how to work with auto-generated MVVM methods
Basic question, but I can't find the answer in the docs for the Entry
control.
CommunityToolkit.MvvV
comes with these awesome auto-generated methods. Here is one that I want to use with the Entry
control:partial void OnNameChanged(string? value)
Or:partial void OnNameChanging(string? value)
The problem is that it works... too well. When I set up either one of the above methods to work with an Entry
control, the method is called as soon as a single character is typed into the control's user-input field, whereas the obvious behavior is that the method should trigger when the user hits Enter
or clicks away.
In the docs there are ways to deal with this, but none of them appear to be MvvM
(I very well could be misinterpreting or simply missing the fix).
Here is the World's Simplest Example of the error:
I have the ViewModel. This is the entire class:
public partial class CheckboxMethodPageViewModel : ObservableObject
{
[ObservableProperty]
private string name;
partial void OnNameChanged(string value)
{
throw new NotImplementedException();
}
}
I have the Entry
control in the Xaml. This is literally all of the code in the XAML:
<VerticalStackLayout>
<Entry Placeholder="Enter a string value."
Text={Binding Name}/>
</VerticalStackLayout>
When I enter a character into the Entry
's text field it triggers the method OnNameChanged( )
(same thing happens with OnNameChanging( )
). There doesn't appear to be a way to make it trigger after the user has hit Enter
.
Is this just something that MvvM
hasn't caught up to?
- How to open picker in xamarin form on button clickI am using below code but it is not working for me public void OpenPiker(){ Picker picker = new Picker(); picker.ItemsSource = Mylist; picker.Focus(); }
How to open picker in xamarin form on button click
I am using below code but it is not working for me
public void OpenPiker(){
Picker picker = new Picker();
picker.ItemsSource = Mylist;
picker.Focus();
}
- InputBindings work only when focusedI have designed a reuseable usercontrol. It contains UserControl.InputBindings. It is quite simple as it only contains a label and a button (and new properties etc.) When I use the control in my window it works well. But the key binding only works when focussed. When one control has a binding to alt+f8 this shortcut only works when it is focussed. When the other one with its own binding is focussed, that one works but alt+f8 no more. When none of the controls has the focus, nothing works. How
InputBindings work only when focused
I have designed a reuseable usercontrol. It contains UserControl.InputBindings. It is quite simple as it only contains a label and a button (and new properties etc.)
When I use the control in my window it works well. But the key binding only works when focussed. When one control has a binding to alt+f8 this shortcut only works when it is focussed. When the other one with its own binding is focussed, that one works but alt+f8 no more. When none of the controls has the focus, nothing works.
How can I achieve that my usercontrol defines window-wide keybindings?
Especially following MVVM design pattern (Caliburn.Micro used) but any help is appreciated.
The XAML of the user control:
<UserControl x:Class="MyApp.UI.Controls.FunctionButton"
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:MyApp.UI.Controls"
xmlns:cm="http://www.caliburnproject.org"
x:Name="Root"
Focusable="True"
mc:Ignorable="d"
d:DesignHeight="60" d:DesignWidth="120">
<UserControl.Resources>
...
</UserControl.Resources>
<UserControl.InputBindings>
<KeyBinding Key="{Binding ElementName=Root, Path=FunctionKey}" Modifiers="{Binding ElementName=Root, Path=KeyModifiers}" Command="{Binding ElementName=Root, Path=ExecuteCommand}" />
</UserControl.InputBindings>
<DockPanel LastChildFill="True">
<TextBlock DockPanel.Dock="Top" Text="{Binding ElementName=Root, Path=HotkeyText}" />
<Button DockPanel.Dock="Bottom" Content="{Binding ElementName=Root, Path=Caption}" cm:Message.Attach="[Event Click] = [Action ExecuteButtonCommand($executionContext)]" cm:Action.TargetWithoutContext="{Binding ElementName=Root}" />
</DockPanel>
</UserControl>
Example usage:
<Grid>
<c:FunctionButton Width="75" Height="75" Margin="10,10,0,0" VerticalAlignment="Top" HorizontalAlignment="Left" FunctionKey="F1" ShiftModifier="True" cm:Message.Attach="[Event Execute] = [Action Button1Execute]" />
<c:FunctionButton Width="75" Height="75" Margin="10,90,0,0" VerticalAlignment="Top" HorizontalAlignment="Left" FunctionKey="F2" ShiftModifier="True" cm:Message.Attach="[Event Execute] = [Action Button2Execute]" />
</Grid>
As said each button works (Execute gets fired) on mouse click and when focused I can use space to activate the button and the input binding of the focused button works but never of the un-focused.