Type ObservableDictionary cannot be found in visual studio community 2017 - c#

In the Visual Studio Community MainPage.xaml.cs file containing the following code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.UI.Xaml.Media.Animation;
using System.Collections.ObjectModel;
// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace App2
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
Random random = new Random();
///private NavigationHelper navigationHelper; ///not needed in Visual Studio 2017
private ObservableDictionary defaultViewModel = new ObservableDictionary();
public MainPage()
{
this.InitializeComponent();
}
private void startButton_Click(object sender, RoutedEventArgs e)
{
AddEnemy();
}
private void AddEnemy()
{
ContentControl enemy = new ContentControl();
enemy.Template = Resources["EnemyTemplate"] as ControlTemplate;
AnimateEnemy(enemy, 0, playArea.ActualWidth - 100, "(Canvas.Left)");
AnimateEnemy(enemy, random.Next((int)playArea.ActualHeight - 100), random.Next((int)playArea.ActualHeight - 100), "(Canvas.Top)");
playArea.Children.Add(enemy);
}
private void AnimateEnemy(ContentControl enemy, double from, double to, string propertyToAnimate)
{
Storyboard storyboard = new Storyboard() { AutoReverse = true, RepeatBehavior = RepeatBehavior.Forever };
DoubleAnimation animation = new DoubleAnimation()
{
From = from,
To = to,
Duration = new Duration(TimeSpan.FromSeconds(random.Next(4, 6)))
};
Storyboard.SetTarget(animation, enemy);
Storyboard.SetTargetProperty(animation, propertyToAnimate);
storyboard.Children.Add(animation);
storyboard.Begin();
}
}
}
... the line
private ObservableDictionary defaultViewModel = new ObservableDictionary();
produces the following error message:
Error CS0246 The type or namespace name 'ObservableDictionary' could not
be found (are you missing a using directive or an assembly reference?)
What library am I supposed to include to make this error message go away?

I know that this question is too old, but Head First C# used a Common folder, that has this ReadMe:
The Common directory contains classes and XAML styles that simplify application development.
These are not merely convenient, but are required by most Visual
Studio project and item templates. If you need a variation on one of
the styles in StandardStyles it is recommended that you make a copy in
your own resource dictionary. When right-clicking on a styled control
in the design surface the context menu includes an option to Edit a
Copy to simplify this process.
Classes in the Common directory form part of your project and may be
further enhanced to meet your needs. Care should be taken when
altering existing methods and properties as incompatible changes will
require corresponding changes to code included in a variety of Visual
Studio templates. For example, additional pages added to your project
are written assuming that the original methods and properties in
Common classes are still present and that the names of the types have
not changed.
In the VS2013 solution common folder (there is a VS2012 too, with totally different classes) these are the cs files:
To use these classes you have to add:
using Save_the_Humans.Common;
HFC# had not once in the book cited or referred to these classes; I'm assuming that they were boilerplate code at that time; they wrap some Interfaces and Dictionaries:
public class ObservableDictionary : IObservableMap<string, object>
{
private class ObservableDictionaryChangedEventArgs : IMapChangedEventArgs<string>
{
public ObservableDictionaryChangedEventArgs(CollectionChange change, string key)
{
this.CollectionChange = change;
this.Key = key;
}
public CollectionChange CollectionChange { get; private set; }
public string Key { get; private set; }
...
You can get the C# code - not only the common folder - from them with the VS2012 version too or from my repository with only VS2013; from their repository you cannot open or import into VS2017 - at least I couldn't; mine is already fresh made with VS2017.
Hope it helps someone.

Related

Caliburn.Micro BindableCollection is not updating in View code using code behind to set up bindings

I want to create a WPF application using Caliburn.Micro MVVM. One of the Views should make a nice drawing of data obtained for the ViewModel. In the View, I want to do the drawing in code behind. I use scalar dependency properties. That works fine. I also can use data stored in a BindableCollection (LocationList in the example code below). What not works is updating the DependencyProperty if I add new elements to the BindableCollection. It must be a stupid mistake, but I do not see it. I created a demo application, leaving out as much as possible. It is a standard Caliburn.Micro setup. I do not show the Bootstrapper, ShellView and ShellViewModel here. They are the general starter configurations.
The ViewModel looks like this:
using Caliburn.Micro;
using System.Collections.Generic;
namespace BindingCodeBehind.ViewModels
{
public class DemoViewModel : Screen
{
private BindableCollection<string> _locationList;
public BindableCollection<string> LocationList
{
get { return _locationList; }
set
{
_locationList = value;
NotifyOfPropertyChange(()=>LocationList);
}
}
public DemoViewModel()
{
LocationList = new BindableCollection<string>();
}
protected override void OnViewLoaded(object view)
{
base.OnViewLoaded(view);
for (int i = 0; i < 3; i++)
{
// BindableCollection supports AddRange, but not Add.
LocationList.AddRange( new List<string>{$"Test nr {i}"});
// LocationList.Add($"Test nr {i}");
}
NotifyOfPropertyChange(()=>LocationList.Count);
}
}
}
LocationList is initialized in the constructor. I add data in the OnViewLoaded event handler.
The XAML code of the View is nothing special, just a scaffolded UserControl, nothing added. The code behind looks like this:
using Caliburn.Micro;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;
namespace BindingCodeBehind.Views
{
public partial class DemoView : UserControl
{
public BindableCollection<string> LocationList
{
get { return (BindableCollection<string>) GetValue(LocationListProperty); }
set { SetValue(LocationListProperty, value);}
}
public static readonly DependencyProperty LocationListProperty =
DependencyProperty.Register("LocationList",
typeof(BindableCollection<string>),
typeof(DemoView),
new FrameworkPropertyMetadata(null,
FrameworkPropertyMetadataOptions.AffectsRender,
new PropertyChangedCallback(OnLocationListChanged)));
public DemoView()
{
InitializeComponent();
var myBinding = new Binding
{
Mode = BindingMode.TwoWay,
Path = new PropertyPath("LocationList"),
NotifyOnSourceUpdated = true
};
BindingOperations.SetBinding(this, LocationListProperty, myBinding);
}
protected override void OnRender(DrawingContext drawingContext)
{
// Data from LocationLst should be used in drawing
}
private static void OnLocationListChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
// I assume this called if LocationList changes
}
}
}
In the code a dependency property LocationList is created. In the constructor I created a binding for this property. In the debugger, I ca see this actually works. OnLocationListChanged should be invoked if this list changes. I see this is called when I create the LocationList in the constructor of the ViewModel, but the handle is not called again, when I add three elements to the LocationList. Therefore, I think the issue is somewhere in the handling of INotifyChange. To get a better understanding, I looked up the source code of the BindableCollection class and saw the Add method is not implemented, so I changed in the ViewModel my code to use the AddRange method, just to be sure but it does not help.
I tried a lot of things, but I am completely out of ideas on how to get this working. I really hope someone can help me out. Basically, all this should cause my application the call OnRender again to update the drawing. This is my first WPF drawing application and my first Caliburn.Micro application, so this all is still new for me.
My development environment: Visual Studio 2019, community edition, .Net Core 3.1 C# 8.0, Windows10. All updated with the latest patches.
Your assumption that "OnLocationListChanged should be invoked if this list changes" is wrong.
A callback of a dependency property is only called when the property itself is set to a new value, i.e. when you assign it to a new instance of a BindableCollection<string>.
It's doesn't get invoked when you add items to or remove items from the collection. There is a CollectionChanged event that you can handle to in response to individual items getting added or removed.

I get an error in C# "The type or namespace name does not exist in namespace"

I get an error in C# "The type or namespace name does not exist in namespace". I checked everywhere but it didn't solve my problem here is the main program
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using Newtonsoft.Json;
using BlockChainMySelf;
using Formatting = Newtonsoft.Json.Formatting;
namespace BlockChainMySelf
{
class Program
{
static void Main(string[] args)
{
var startTime = DateTime.Now;
BlockChainMySelf.BlockChain StepCoin = new BlockChain();
StepCoin.CreateTransaction(new Transaction("Henry", "MaHesh", 10));
StepCoin.CreateTransaction(new Transaction("lkjsdf", "MaADLKHesh", 15));
StepCoin.CreateTransaction(new Transaction("Henry", "MaHesh", 20));
StepCoin.CreateTransaction(new Transaction("Henry", "MaHesh", 60));
StepCoin.ProcessPendingTransactions("Bill");
And here is the class that I want to call
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using Newtonsoft.Json;
using BlockChainMySelf;
using Formatting = Newtonsoft.Json.Formatting;
namespace BlockChainMySelf
{
public class BlockChain
{
IList<Transaction> PendingTransactions = new List<Transaction>();
public IList<Block> Chain { set; get; }
public int Difficulty { set; get; } = 2;
Here are the Screendhots
Main
Class
answerquestion
answerquestion2
The second screenshot in an earlier edit of your question clearly shows the BlockChain class as being 'Miscellaneous Files' in Visual Studio:
The MSDN page for the Miscellaneous Files Project says (emphasis mine):
When a user opens project items, the IDE assigns to the Miscellaneous Files project any items that are not members of any projects in a solution.
Presumably you were in the middle of trying to fix the issue, so you put static in - but that won't work because then you can't create an instance of a BlockChain.
Your question is a duplicate of Visual Studio - project shows up as “Miscellaneous Files”.
The/a solution is to right-click on the bad file in Solution Explorer, remove it from the project, then re-add it, e.g. this answer.
I had this issue... however, I had two classes under the same namespace but in different projects. All I had to do to fix this was to add a reference to the project directly.

Unknown type error in xaml with class derived from ObservableCollection

Based on this example at MSDN, I created a "non-generic custom collection class that derives from ObservableCollection, and constrains it to a specific type." This is used as the ItemsSource property of a listview control. This all works perfectly and the xaml design view displays the sample data I loaded into the custom collection class.
The problem occurs when I try to build the project; I get this error: "Error 1 Unknown type 'ThreadCollection' in XML namespace 'clr-namespace:Messaging_2._0;assembly=Messaging 2.0.WindowsPhone, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' C:\Users\Wesley\Source\Repos\Messenging 2.0\Messaging 2.0\Messaging 2.0\Messaging 2.0.WindowsPhone\MainPage.xaml 14 10 Messaging 2.0.WindowsPhone.
This error originates from the line <c:ThreadCollection x:Key="MainThreadCollection"/> of the xaml code below.
<Page
x:Class="Messaging_2._0.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Messaging_2._0"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:c="clr-namespace:Messaging_2._0"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Page.Resources>
<c:ThreadCollection x:Key="MainThreadCollection"/>
</Page.Resources>
<The code for the listview control is here, I haven't included it because it works as I expect.>
Here is the C# code behind referenced by the xaml:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using System.Collections.ObjectModel;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace Messaging_2._0
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public ThreadCollection MainThreadCollection = new ThreadCollection();
public MainPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
this.DataContext = this;
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached.
/// This parameter is typically used to configure the page.</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
// TODO: Prepare page for display here.
// TODO: If your application contains multiple pages, ensure that you are
// handling the hardware Back button by registering for the
// Windows.Phone.UI.Input.HardwareButtons.BackPressed event.
// If you are using the NavigationHelper provided by some templates,
// this event is handled for you.
}
private void AddThread(object sender, RoutedEventArgs e)
{
MainThreadCollection.Add(new ThreadViewItem() { Name = "Tom Riddle", LatestMessage = "It worked!" });
}
}
public class ThreadCollection : ObservableCollection<ThreadViewItem>
{
public ThreadCollection()
: base()
{
Add(new ThreadViewItem() { Name = "Harry Potter", LatestMessage = "What's up?" });
}
}
public class ThreadViewItem
{
public String Name
{
get;
set;
}
public String LatestMessage
{
get;
set;
}
}
}
Because the design view previews the message from Harry Potter correctly, I think the problem is relatively minor, I just can't figure out what it is exactly.
I would place the ThreadCollection in its own file (preferably ThreadCollection.cs) and place it in its own namespace, like Messaging_2._0.Collections or something similar. Then point the xmlns:c to that namespace.
That will ensure that your class isn't affected by the automatic code generation involved when coding XAML.
If it doesn't solve your issue, the error text might at least be more helpful.

Why can't I use this command in my resource dictionary?

I cannot for the life of me figure out why I cannot create my class in this dictionary. Intellisense isn't picking up my WindowCommand<T> class. I checked the Assembly name and it appears to be correct, no typos in the namespace either. What's making it choke?
WindowCommand.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using Ninject;
using Premier;
using Premier.View;
namespace Premier.Command
{
public class WindowCommand<T> : Command where T : Window
{
private Func<bool> focus;
private int instantiationCount;
public bool IsDialog { get; set; }
public bool Multiple { get; set; }
public WindowCommand()
{
}
public override bool CanExecute(object parameter)
{
return true;
}
public override void Execute(object parameter)
{
var instantiatedOnce = instantiationCount > 0;
if (!Multiple && instantiatedOnce)
{
focus();
return;
}
instantiationCount++;
var w = App.Kernel.Get<T>();
w.Closed += (s, e) => instantiationCount--;
focus = w.Focus;
if (IsDialog)
w.ShowDialog();
else
w.Show();
}
}
}
Windows.xaml:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:c="clr-namespace:Premier.Command;assembly=PremierAutoDataExtractor"
xmlns:v="clr-namespace:Premier.View;assembly=PremierAutoDataExtractor"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<c:WindowCommand x:Key="ReportsPurchased" x:TypeArguments="v:PurchasedReportsView" />
</ResourceDictionary>
x:TypeArguments XAML directive is not supported in XAML 2006 (xml namespace http://schemas.microsoft.com/winfx/2006/xaml/presentation) on non-root XAML elements. If you want to use x:TypeArguments on a non-root XAML element, you should use XAML2009 (xml namespace http://schemas.microsoft.com/netfx/2009/xaml/presentation). However, again it is only supported for non-complied loose XAML.
Text from MSDN Page:
In WPF and when targeting .NET Framework 4, you can use XAML 2009
features together with x:TypeArguments but only for loose XAML (XAML
that is not markup-compiled). Markup-compiled XAML for WPF and the
BAML form of XAML do not currently support the XAML 2009 keywords and
features. If you need to markup compile the XAML, you must operate
under the restrictions noted in the "XAML 2006 and WPF Generic XAML
Usages" section.
So, I am afraid, you cannot use your WindowCommand in a resource dictionary.
Link to MSDN page for more information on x:TypeArguments directive.

error : 'classA' doesnot exist in current context

I started new project of Windows Forms. First page is UserLogin. in form load event I am taking the logintable from database into memory.
I am using a class in which all read and write operations methods are stored.
when I am calling the class in formload event, the error comes "doesnot exist in current context"
I may be missing some references or headerfilename..
Please Help
Thanks in Advance
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.Web;
namespace InvestmentAndReturns
{
public partial class UserLogin : Form
{
public UserLogin()
{
InitializeComponent();
CenterToScreen();
}
public string UserID = null;
private string userPass = null;
public string UserGroup = null;
DataTable UserLoginTable;
int logintry = 1;
public bool LoginStatus = false;
private void Form1_Load(object sender, EventArgs e)
{
txtUserID.Select();
string cmd = "Select * from UserLogin";
UserLoginTable = DbRdRw.SqlDbRead(cmd, "UserLogin");
}
DbRdRw: this is the Class
SqlDbRead: this is read method
i have included that class by directly pasting it in the project folder and then opened solution and then included in the project
It looks like you have copy pasted source file containing definition of DbRdRw from some other project - which mostly means the namespace declaration in the file will be from older project.
Things will work if you change the namespace to your current project InvestmentAndReturns.
However, why are you copy pasting this around? You could make a library dll for your DbRdRw and reference the dll. That way you will keep your source code at one place.

Categories

Resources