Indeed
Indeed
Explore posts from servers
CC#
Created by Indeed on 6/3/2024 in #help
String enums - current consensus
Hi! What is the current consensus on string enum Any special library, Some abstract class that defines helper methods with attributes etc. Example usage:
public enum AuthTokenStatus {
ACTIVE = 'Y',
INACTIVE = 'N'
}
public enum AuthTokenStatus {
ACTIVE = 'Y',
INACTIVE = 'N'
}
28 replies
CC#
Created by Indeed on 5/14/2024 in #help
SQL EFCore
Hi! What's current way to query db for data using raw sql? Im used to doing it this way from Doctrinedb and php Something like MyModel[] x = query("SELECT ..."); Rather than using an orm
16 replies
CC#
Created by Indeed on 12/24/2023 in #help
WPF with html-css alike framework?
Hi! I came back to make some apps for myself in wpf after working for a long time in frontend. and on god - i love the DI and MVVM architecture but I cannot stand XAML for the life of me. Is there something like wpf mvvm but with html and css? I know xamarin supports css, but html?
14 replies
CC#
Created by Indeed on 10/14/2023 in #help
✅ C# Like PHP in terms of live changes
Hi! At work I'm using php with bits of Symphony and Im curious whether there is a way to achieve something similiar in C# in terms of being able to dynamically change endpoints while the program is running and also have endpoints be checked independently - i.e. while modifying one checkpoint all other work
33 replies
CC#
Created by Indeed on 3/3/2023 in #help
❔ .net cli use file-scoped namespace
Hi! Is there a way for the dotnet cli to use file-scoped namespaces? I have .net 7 + c# 11 project but it does not do that sadly
3 replies
CC#
Created by Indeed on 2/28/2023 in #help
❔ Csproj Run npm command side by side with dotnet run
Hi! How can I make csproj run npm run build alongside it rather than before it and then quitting?
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>

<NpmLastInstall>node_modules/.last-install</NpmLastInstall>
</PropertyGroup>

<Target Name="CheckForNpm" BeforeTargets="NpmInstall">
<Exec Command="npm -v" ContinueOnError="true">
<Output TaskParameter="ExitCode" PropertyName="ErrorCode" />
</Exec>
<Error Condition="'$(ErrorCode)' != '0'" Text="You must install NPM to build this project" />
</Target>

<Target Name="NpmInstall" BeforeTargets="BuildCSS" Inputs="package.json" Outputs="$(NpmLastInstall)">
<Exec Command="npm install" />
<Touch Files="$(NpmLastInstall)" AlwaysCreate="true" />
</Target>

<Target Name="BuildCSS" BeforeTargets="Compile">
<Exec Command="npm run build" Condition=" '$(Configuration)' == 'Debug' " />
<Exec Command="npm run release" Condition=" '$(Configuration)' == 'Release' " />
</Target>
</Project>
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>

<NpmLastInstall>node_modules/.last-install</NpmLastInstall>
</PropertyGroup>

<Target Name="CheckForNpm" BeforeTargets="NpmInstall">
<Exec Command="npm -v" ContinueOnError="true">
<Output TaskParameter="ExitCode" PropertyName="ErrorCode" />
</Exec>
<Error Condition="'$(ErrorCode)' != '0'" Text="You must install NPM to build this project" />
</Target>

<Target Name="NpmInstall" BeforeTargets="BuildCSS" Inputs="package.json" Outputs="$(NpmLastInstall)">
<Exec Command="npm install" />
<Touch Files="$(NpmLastInstall)" AlwaysCreate="true" />
</Target>

<Target Name="BuildCSS" BeforeTargets="Compile">
<Exec Command="npm run build" Condition=" '$(Configuration)' == 'Debug' " />
<Exec Command="npm run release" Condition=" '$(Configuration)' == 'Release' " />
</Target>
</Project>
My scripts
"scripts": {
"build": "cross-env NODE_ENV=development npx tailwindcss -i ./Styles/site.css -o ./wwwroot/css/site.css --watch",
"watch": "cross-env NODE_ENV=development npx tailwindcss -i ./Styles/site.css -o ./wwwroot/css/site.css --watch",
"release": "cross-env NODE_ENV=production npx tailwindcss -i ./Styles/site.css -o ./wwwroot/css/site.css --minify"
},
"scripts": {
"build": "cross-env NODE_ENV=development npx tailwindcss -i ./Styles/site.css -o ./wwwroot/css/site.css --watch",
"watch": "cross-env NODE_ENV=development npx tailwindcss -i ./Styles/site.css -o ./wwwroot/css/site.css --watch",
"release": "cross-env NODE_ENV=production npx tailwindcss -i ./Styles/site.css -o ./wwwroot/css/site.css --minify"
},
26 replies
CC#
Created by Indeed on 2/25/2023 in #help
❔ WPF slide in from right to left Storyboard
Hi! Im trying to make my object appearing be animated, however i get
Severity Code Description Project File Line Suppression State
Error XDG0010 Cannot freeze this Storyboard timeline tree for use across threads. WPFTodo C:\Users\Indeed\Desktop\Stuff\Repositories\c#\WPFTodo\Views\TodoDisplayView.xaml 133
Severity Code Description Project File Line Suppression State
Error XDG0010 Cannot freeze this Storyboard timeline tree for use across threads. WPFTodo C:\Users\Indeed\Desktop\Stuff\Repositories\c#\WPFTodo\Views\TodoDisplayView.xaml 133
<Grid
x:Name="ContentGrid"
Grid.Column="1"
RenderTransformOrigin="1,0"
Visibility="{Binding DisplayMore, Converter={StaticResource boolToVis}}">
<Grid.RenderTransform>
<TranslateTransform X="{Binding ActualWidth, ElementName=ContentGrid}" />
</Grid.RenderTransform>
<Grid.Style>
<Style>
<Style.Triggers>
<DataTrigger
Binding="{Binding IsVisible, RelativeSource={RelativeSource Self}}"
Value="True">
<DataTrigger.EnterActions>
<BeginStoryboard Storyboard="{StaticResource SlideInRightToLeftStoryboard}" />
</DataTrigger.EnterActions>
<DataTrigger.ExitActions>
<BeginStoryboard Storyboard="{StaticResource SlideOutLeftToRightStoryboard}" />
</DataTrigger.ExitActions>
</DataTrigger>
</Style.Triggers>
</Style>
</Grid.Style>
</Grid>
<Grid
x:Name="ContentGrid"
Grid.Column="1"
RenderTransformOrigin="1,0"
Visibility="{Binding DisplayMore, Converter={StaticResource boolToVis}}">
<Grid.RenderTransform>
<TranslateTransform X="{Binding ActualWidth, ElementName=ContentGrid}" />
</Grid.RenderTransform>
<Grid.Style>
<Style>
<Style.Triggers>
<DataTrigger
Binding="{Binding IsVisible, RelativeSource={RelativeSource Self}}"
Value="True">
<DataTrigger.EnterActions>
<BeginStoryboard Storyboard="{StaticResource SlideInRightToLeftStoryboard}" />
</DataTrigger.EnterActions>
<DataTrigger.ExitActions>
<BeginStoryboard Storyboard="{StaticResource SlideOutLeftToRightStoryboard}" />
</DataTrigger.ExitActions>
</DataTrigger>
</Style.Triggers>
</Style>
</Grid.Style>
</Grid>
4 replies
CC#
Created by Indeed on 2/6/2023 in #help
❔ WPF Converter Infinite call
Hi! I am trying to make a converter that makes fontsize relative to the binding by ratio the problem is that it is jumping around as seen in the picture my xaml:
<UserControl.Resources>
<converters:RelativeFontSizeConverter
x:Key="RelativeFontSizeConverter"
WhenInvalid="15" />
<converters:MathConverter x:Key="MathConverter" />
</UserControl.Resources>
<Grid Margin="14,14">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="auto" />
</Grid.ColumnDefinitions>

<Grid Grid.Column="0">
<Grid.RowDefinitions>
<RowDefinition Height="3*" />
<RowDefinition Height="2*" />
</Grid.RowDefinitions>

<TextBlock
Grid.Row="0"
d:Text="Tell Mark"
FontSize="{Binding ActualHeight, ConverterParameter='0.7', Converter={StaticResource RelativeFontSizeConverter}, RelativeSource={RelativeSource Self}}"
FontWeight="SemiBold"
Foreground="{StaticResource BrushFgDefault}"
Text="{Binding Todo.Title}"
TextTrimming="CharacterEllipsis" />

<TextBlock
Grid.Row="1"
d:Text="Tell Mark the details of the project that he has been recently included in"
FontSize="{Binding ActualHeight, ConverterParameter='0.7', Converter={StaticResource RelativeFontSizeConverter}, RelativeSource={RelativeSource Self}}"
Foreground="{StaticResource BrushFgMuted}"
Text="{Binding Todo.Description}"
TextWrapping="Wrap" />
</Grid>


<!-- scalable square button up to 80x80 -->
<Viewbox
Grid.Column="1"
MaxWidth="80"
MaxHeight="80"
VerticalAlignment="Top"
Stretch="Uniform">
...
</Viewbox>
</Grid>
</Grid>
<UserControl.Resources>
<converters:RelativeFontSizeConverter
x:Key="RelativeFontSizeConverter"
WhenInvalid="15" />
<converters:MathConverter x:Key="MathConverter" />
</UserControl.Resources>
<Grid Margin="14,14">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="auto" />
</Grid.ColumnDefinitions>

<Grid Grid.Column="0">
<Grid.RowDefinitions>
<RowDefinition Height="3*" />
<RowDefinition Height="2*" />
</Grid.RowDefinitions>

<TextBlock
Grid.Row="0"
d:Text="Tell Mark"
FontSize="{Binding ActualHeight, ConverterParameter='0.7', Converter={StaticResource RelativeFontSizeConverter}, RelativeSource={RelativeSource Self}}"
FontWeight="SemiBold"
Foreground="{StaticResource BrushFgDefault}"
Text="{Binding Todo.Title}"
TextTrimming="CharacterEllipsis" />

<TextBlock
Grid.Row="1"
d:Text="Tell Mark the details of the project that he has been recently included in"
FontSize="{Binding ActualHeight, ConverterParameter='0.7', Converter={StaticResource RelativeFontSizeConverter}, RelativeSource={RelativeSource Self}}"
Foreground="{StaticResource BrushFgMuted}"
Text="{Binding Todo.Description}"
TextWrapping="Wrap" />
</Grid>


<!-- scalable square button up to 80x80 -->
<Viewbox
Grid.Column="1"
MaxWidth="80"
MaxHeight="80"
VerticalAlignment="Top"
Stretch="Uniform">
...
</Viewbox>
</Grid>
</Grid>
24 replies
CC#
Created by Indeed on 2/3/2023 in #help
❔ WPF Cannot find child when it's there
Hi! I am working on my own RoundedCorners attachedproperty however I have stumbled upon a problem Problem: When an item that starts invisible goes visible the effect is not applied I've tried experimenting with Loaded and IsVisibleChanged events, where IsVisibleChanged actually fires on the visibility change and the Loaded fires on the start But when IsVisibleChanged fires there are still no children detected in a tree to even try to look for a border
10 replies
CC#
Created by Indeed on 1/29/2023 in #help
❔ WPF Border TemplateBinding
Hi! I've created such style for most of my controls to have rounded corners however i would like for them to be modifiable ive written an attached property however i do not have a way to bind it style
<Style x:Key="RoundBorder">
<Style.Resources>
<Style TargetType="Border">
<Setter Property="CornerRadius" Value="3" />
</Style>
</Style.Resources>
</Style>
<Style x:Key="RoundBorder">
<Style.Resources>
<Style TargetType="Border">
<Setter Property="CornerRadius" Value="3" />
</Style>
</Style.Resources>
</Style>
property
public static class ThemeProperties {
public static float GetRoundedCornerRadius(DependencyObject obj) {
return (float)obj.GetValue(RoundedCornerRadiusProperty);
}
public static void SetRoundedCornerRadius(DependencyObject obj, float value) {
obj.SetValue(RoundedCornerRadiusProperty, value);
}
public static readonly DependencyProperty RoundedCornerRadiusProperty =
DependencyProperty.RegisterAttached("RoundedCornerRadius", typeof(float), typeof(ThemeProperties), new PropertyMetadata(3f));
}
public static class ThemeProperties {
public static float GetRoundedCornerRadius(DependencyObject obj) {
return (float)obj.GetValue(RoundedCornerRadiusProperty);
}
public static void SetRoundedCornerRadius(DependencyObject obj, float value) {
obj.SetValue(RoundedCornerRadiusProperty, value);
}
public static readonly DependencyProperty RoundedCornerRadiusProperty =
DependencyProperty.RegisterAttached("RoundedCornerRadius", typeof(float), typeof(ThemeProperties), new PropertyMetadata(3f));
}
normally one would use a template binding in the style but i cant do that while keeping the style generic
2 replies
CC#
Created by Indeed on 1/25/2023 in #help
✅ XML docs not all exceptions included
Hi! It appears not all exceptions are included in xml docs Is there a way to go about it?
namespace WPFWeather.Services.WeatherProvider;
public interface IWeatherProvider {
/// <summary>
/// Fetches WeatherData for the given location
/// </summary>
/// <param name="location"></param>
/// <param name="from"></param>
/// <param name="to"></param>
/// <returns></returns>
/// <exception cref="ArgumentException"></exception>
/// <exception cref="System.Net.HttpRequestException"></exception> //not included
public Task<IEnumerable<WeatherData>> GetWeatherAsync(Location location, DateTime from, DateTime to);
}
namespace WPFWeather.Services.WeatherProvider;
public interface IWeatherProvider {
/// <summary>
/// Fetches WeatherData for the given location
/// </summary>
/// <param name="location"></param>
/// <param name="from"></param>
/// <param name="to"></param>
/// <returns></returns>
/// <exception cref="ArgumentException"></exception>
/// <exception cref="System.Net.HttpRequestException"></exception> //not included
public Task<IEnumerable<WeatherData>> GetWeatherAsync(Location location, DateTime from, DateTime to);
}
10 replies
CC#
Created by Indeed on 1/24/2023 in #help
✅ Shorten inline switch with multiple passing values
Hi! Would there be a way to shorten this? In python, their pattern matching would have a simple in [x1,x2,x3]
5 replies
CC#
Created by Indeed on 1/23/2023 in #help
✅ WPF Store Singleton Action PropertyChanged optimization
Hi! I have a singleton in my app responsible for weather management currently each of my properties on the object has an Action<T> where T is property's type, however that means i have to write an action for each property is there a better way?
public class AppStore {
private List<WeatherData> _weatherForecasts;
public IEnumerable<WeatherData> WeatherForecasts => _weatherForecasts;
public Location? Location { get; private set; }
public event Action<Location?> LocationChanged;
public event Action<IEnumerable<WeatherData>> WeatherForecastsChanged;

public bool IsLoading { get; internal set; }
public bool IsFetching { get; internal set; }
public event Action<bool> LoadingChanged;
public event Action<bool> FetchingChanged;

private async Task FetchWeather() {
if (Location == null) {
_weatherForecasts.Clear();
WeatherForecastsChanged?.Invoke(_weatherForecasts);
return;
}

SetLoading(true);
IEnumerable<WeatherData> weather = await _weatherProvider.GetWeatherAsync(Location, DateTime.Now, DateTime.Now.AddDays(3));
_weatherForecasts = weather.ToList();
WeatherForecastsChanged?.Invoke(_weatherForecasts);
SetLoading(false);
}

private void SetLoading(bool value) {
if (IsLoading == value) return;

IsLoading = value;
LoadingChanged?.Invoke(value);
}

//...
}
public class AppStore {
private List<WeatherData> _weatherForecasts;
public IEnumerable<WeatherData> WeatherForecasts => _weatherForecasts;
public Location? Location { get; private set; }
public event Action<Location?> LocationChanged;
public event Action<IEnumerable<WeatherData>> WeatherForecastsChanged;

public bool IsLoading { get; internal set; }
public bool IsFetching { get; internal set; }
public event Action<bool> LoadingChanged;
public event Action<bool> FetchingChanged;

private async Task FetchWeather() {
if (Location == null) {
_weatherForecasts.Clear();
WeatherForecastsChanged?.Invoke(_weatherForecasts);
return;
}

SetLoading(true);
IEnumerable<WeatherData> weather = await _weatherProvider.GetWeatherAsync(Location, DateTime.Now, DateTime.Now.AddDays(3));
_weatherForecasts = weather.ToList();
WeatherForecastsChanged?.Invoke(_weatherForecasts);
SetLoading(false);
}

private void SetLoading(bool value) {
if (IsLoading == value) return;

IsLoading = value;
LoadingChanged?.Invoke(value);
}

//...
}
12 replies
CC#
Created by Indeed on 1/19/2023 in #help
❔ WPF export binding into resources
Hi! How can I define a binding with the ability to use intellisense
<UserControl.Resources>
<Binding x:Key="SelfContext">
<Binding.RelativeSource>
<RelativeSource AncestorType="{x:Type local:WeatherHomeView}" Mode="FindAncestor" />
</Binding.RelativeSource>
</Binding>
</UserControl.Resources>
<UserControl.Resources>
<Binding x:Key="SelfContext">
<Binding.RelativeSource>
<RelativeSource AncestorType="{x:Type local:WeatherHomeView}" Mode="FindAncestor" />
</Binding.RelativeSource>
</Binding>
</UserControl.Resources>
<Button DataContext="{StaticResource SelfContext}"/>
<Button DataContext="{StaticResource SelfContext}"/>
it does not provide autocomplete but
<Button DataContext="{Binding RelativeSource={RelativeSource AncestorType=local:WeatherHomeView}}"/>
<Button DataContext="{Binding RelativeSource={RelativeSource AncestorType=local:WeatherHomeView}}"/>
does
2 replies
CC#
Created by Indeed on 1/19/2023 in #help
❔ WPF multiple data contexts
Hi! In my wpf app i need to have view-specific commands but i am already using my separate ViewModel (MVVM) as a data context? How can I achieve it wanting a button do something view-specific but also something on the model?
<Button>
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<i:InvokeCommandAction Command="{Binding ViewModelCommand}" />
<i:InvokeCommandAction Command="{Binding ViewCommand}" /> //
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
<Button>
<i:Interaction.Triggers>
<i:EventTrigger EventName="Click">
<i:InvokeCommandAction Command="{Binding ViewModelCommand}" />
<i:InvokeCommandAction Command="{Binding ViewCommand}" /> //
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
54 replies
CC#
Created by Indeed on 1/15/2023 in #help
❔ WPF NavigationService Implement NavigateBack
Hi! I am stuck on a problem of navigating back my navigation singleton
public class NavigationStore {
private ViewModelBase? _currentViewModel;
public ViewModelBase? CurrentViewModel {
get => _currentViewModel;
set {
_currentViewModel?.Dispose();
_currentViewModel = value;
OnCurrentViewModelChanged();
}
}

public event Action CurrentViewModelChanged;

private void OnCurrentViewModelChanged() {
CurrentViewModelChanged?.Invoke();
}
}
public class NavigationStore {
private ViewModelBase? _currentViewModel;
public ViewModelBase? CurrentViewModel {
get => _currentViewModel;
set {
_currentViewModel?.Dispose();
_currentViewModel = value;
OnCurrentViewModelChanged();
}
}

public event Action CurrentViewModelChanged;

private void OnCurrentViewModelChanged() {
CurrentViewModelChanged?.Invoke();
}
}
navigation service
namespace WPFWeather.Services.NavigationService;
public class NavigationService<TViewModel> where TViewModel : ViewModelBase {
private readonly NavigationStore _navigationStore;
private readonly Func<TViewModel> _createViewModel;

public NavigationService(NavigationStore navigationStore, Func<TViewModel> createViewModel) {
_navigationStore = navigationStore;
_createViewModel = createViewModel;
}

public void Navigate() {
_navigationStore.CurrentViewModel = _createViewModel();
}
}
namespace WPFWeather.Services.NavigationService;
public class NavigationService<TViewModel> where TViewModel : ViewModelBase {
private readonly NavigationStore _navigationStore;
private readonly Func<TViewModel> _createViewModel;

public NavigationService(NavigationStore navigationStore, Func<TViewModel> createViewModel) {
_navigationStore = navigationStore;
_createViewModel = createViewModel;
}

public void Navigate() {
_navigationStore.CurrentViewModel = _createViewModel();
}
}
that i register to DI
services.AddTransient<WeatherHomeViewModel>();
services.AddSingleton<Func<WeatherHomeViewModel>>((s) => () => s.GetRequiredService<WeatherHomeViewModel>());
services.AddSingleton<NavigationService<WeatherHomeViewModel>>();

services.AddTransient<WelcomeViewModel>();
services.AddSingleton<Func<WelcomeViewModel>>((s) => () => s.GetRequiredService<WelcomeViewModel>());
services.AddSingleton<NavigationService<WelcomeViewModel>>();
services.AddTransient<WeatherHomeViewModel>();
services.AddSingleton<Func<WeatherHomeViewModel>>((s) => () => s.GetRequiredService<WeatherHomeViewModel>());
services.AddSingleton<NavigationService<WeatherHomeViewModel>>();

services.AddTransient<WelcomeViewModel>();
services.AddSingleton<Func<WelcomeViewModel>>((s) => () => s.GetRequiredService<WelcomeViewModel>());
services.AddSingleton<NavigationService<WelcomeViewModel>>();
and then inject
public SetLocationViewModel(IWeatherProvider weatherProvider, AppStore appStore, NavigationService<WeatherHomeViewModel> weatherHomeNavigationService)
public SetLocationViewModel(IWeatherProvider weatherProvider, AppStore appStore, NavigationService<WeatherHomeViewModel> weatherHomeNavigationService)
However using this architecture I cannot implement going back
16 replies
CC#
Created by Indeed on 1/15/2023 in #help
❔ JsonDeserializer letting null for string type
Hi! I'm facing an issue where when deserializing json, the parser allows a null for string which breaks my app. Can i somehow specify that it is not to be null?
{"Location":{"CityName":null,"Latitude":0,"Longitude":0}}
{"Location":{"CityName":null,"Latitude":0,"Longitude":0}}
public class PersistentData {
public Location? Location { get; set; }
}

public class Location {
public string CityName { get; internal set; }
public double Latitude { get; internal set; }
public double Longitude { get; internal set; }
}
public class PersistentData {
public Location? Location { get; set; }
}

public class Location {
public string CityName { get; internal set; }
public double Latitude { get; internal set; }
public double Longitude { get; internal set; }
}
15 replies
CC#
Created by Indeed on 1/15/2023 in #help
Wait for async function in synchronous context for X time until cancel
Hi! How can i wait X time for this function to finish or otherwise throw/cancel/return something This function comes from an outside library
public bool ValidateAddress(Address address) {
try {
//wait for x or throw
weatherApi.GetCurrentWeatherAsync(cityName: address.CityName);
return true;
}
catch {
return false;
}
}
public bool ValidateAddress(Address address) {
try {
//wait for x or throw
weatherApi.GetCurrentWeatherAsync(cityName: address.CityName);
return true;
}
catch {
return false;
}
}
Only things I see are with usage of await but i need this method to be synchronous
6 replies
CC#
Created by Indeed on 1/14/2023 in #help
❔ Serialize inheriting types as a parent type
Hi! I have this class to group all localization types
public class Location {
}
public class Location {
}
sample localization type
public class Address : Location {
public string CityName { get; }

public Address(string cityName) {
CityName = cityName;
}

public override string ToString() {
return CityName;
}
}
public class Address : Location {
public string CityName { get; }

public Address(string cityName) {
CityName = cityName;
}

public override string ToString() {
return CityName;
}
}
and when i try to serialize it
public class PersistentData {
public Location? Location { get; set; }
}
public class PersistentData {
public Location? Location { get; set; }
}
data.Location = new Address("Kraków");
string json = JsonSerializer.Serialize(data);
File.WriteAllText(storageFilePath, json);
data.Location = new Address("Kraków");
string json = JsonSerializer.Serialize(data);
File.WriteAllText(storageFilePath, json);
I get
{
"Location": {}
}
{
"Location": {}
}
8 replies
CC#
Created by Indeed on 1/13/2023 in #help
❔ Class with parameter as a generic parameter
Hi! I'm trying to write a navigation system in wpf My setup rn using default constructor is
public class ViewModelBase : INotifyPropertyChanged {
public event PropertyChangedEventHandler PropertyChanged;

protected void OnPropertyChanged(string propertyName) {
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

public virtual void Dispose() { }
}
public class ViewModelBase : INotifyPropertyChanged {
public event PropertyChangedEventHandler PropertyChanged;

protected void OnPropertyChanged(string propertyName) {
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

public virtual void Dispose() { }
}
public class NavigationService<TViewModel> where TViewModel : ViewModelBase {
private readonly NavigationStore _navigationStore;
private readonly Func<TViewModel> _createViewModel;

public NavigationService(NavigationStore navigationStore, Func<TViewModel> createViewModel) {
_navigationStore = navigationStore;
_createViewModel = createViewModel;
}

public void Navigate() {
_navigationStore.CurrentViewModel = _createViewModel();
}
}
public class NavigationService<TViewModel> where TViewModel : ViewModelBase {
private readonly NavigationStore _navigationStore;
private readonly Func<TViewModel> _createViewModel;

public NavigationService(NavigationStore navigationStore, Func<TViewModel> createViewModel) {
_navigationStore = navigationStore;
_createViewModel = createViewModel;
}

public void Navigate() {
_navigationStore.CurrentViewModel = _createViewModel();
}
}
however i want to change it so each ViewModelBase has a public custom constructor like TViewModel.NavigateTo() that returns its instance to be able to define some common logic between navigables I've tried to do
public interface Navigable<TViewModel> where TViewModel : ViewModelBase {
TViewModel NavigatedTo();
}
public interface Navigable<TViewModel> where TViewModel : ViewModelBase {
TViewModel NavigatedTo();
}
public class NavigationService<Navigable<TViewModel>> where TViewModel : ViewModelBase {
public class NavigationService<Navigable<TViewModel>> where TViewModel : ViewModelBase {
but it breaks
10 replies