I've custom control in shared project (resource dictionary in shared project).
Everything works fine in run time, xaml designer however throws exception:
Cannot locate resource 'mycontrol.xaml'.
The problem occurs when loading style for control:
public class MyControl: Control
{
public MyControl()
{
Resources = new ResourceDictionary() { Source = new Uri("pack://application:,,,/mycontrol.xaml") };
Style = (Style)Resources["somekey"];
}
}
Why does it works in run-time and doesn't during design time?
I can detect design time, but what to do then?
The WPF designer seems to have problem when loading xaml files from other projects. Could you try to load the xaml file using this annotation:
pack://application:,,,/PROJECTNAMESPACE;component/mycontrol.xaml
I would try
Uri res = new Uri("pack://siteoforigin:,,,/mycontrol.xaml", UriKind.Relative);
Resources.MergedDictionaries.Add(new ResourceDictionary() { Source = res });
Related
I have a behavior for Window as follows
<Window>
<my:Notify x:Name="Not"/>
<behaviors:Interaction.Behaviors>
<behavior:RebuildBehavior Element="{Binding ElementName=Not}" />
</behaviors:Interaction.Behaviors>
<Window>
now i want to write this code in code behind, so i used this code:
in Notify.cs (Loaded Event):
RebuildBehavior behavior = new RebuildBehavior();
behavior.Element = this;
Interaction.GetBehaviors(this).Add(behavior);
But my app crashes in the last line Interaction.GetBehaviors(this).Add(behavior);
System.Resources.MissingManifestResourceException: 'Could not find the
resource "ExceptionStringTable.resources" among the resources "
Did I write the correct code?
UPDATE:
I moved codes to window.cs (Loaded event)
RebuildBehavior behavior = new RebuildBehavior();
behavior.Element = Notify.Instance;
Interaction.GetBehaviors(this).Add(behavior);
crash fixed but not working
The following code would be the equivalent of your XAML markup:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
RebuildBehavior behavior = new RebuildBehavior();
BindingOperations.SetBinding(behavior, RebuildBehavior.ElementProperty,
new Binding() { ElementName ="Not" });
Interaction.GetBehaviors(this).Add(behavior);
}
}
I have a window based application in C#. I am trying to do this for some another language, say arabic.
As we know there is resource file for each form. I have created a global resource file as ResouceFileName.ar-SA.resx . Now I want to change all labels dynamically when I change CultureInfo. If i write in designer file like
static class clsLocalization
{
static ResourceManager resManager = new ResourceManager(typeof(Secure_Browser_CS_Version.Properties.Resources));
public static void applyGlobalResources(Control control,string resource)
{
System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("ar-SA");
control.Text=resManager.GetString(resource);
}
}
// Resource file
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SBMainForm));//Default
//
// settingHdrLbl
//
resources.ApplyResources(this.settingHdrLbl, "settingHdrLbl");
clsLocalization.applyGlobalResources(this.settingHdrLbl, "settingHdrLbl");
this.settingHdrLbl.BackColor = System.Drawing.Color.Transparent;
this.settingHdrLbl.Name = "settingHdrLbl";
This will be reload as default whenever i change in designer file. Pl help me out
I am trying to load a custom control library via reflection in windows 8 Metro C# App, the library is loaded but the styles specified in generic.xaml are not loaded, eventually I tried to load the generic.xaml by making it as an Embedded resource and ,then extracted the Generic.xaml to a location and specified the location of it as uri of a ResourceDictionary object, but it throws an error
"Failed to create a 'System.Type' from the text local:CustomControl1"
I cannot create a nuget package or extension SDK as unfortunately that is not my requirement,
Below sample code I wrote to copy the generic.xaml and load it in a resource dictionary
public sealed class CustomControl1 : Control
{
public CustomControl1()
{
this.DefaultStyleKey = typeof(CustomControl1);
Assembly CurrentAssembly = typeof(CustomControl1).GetTypeInfo().Assembly;
var names = CurrentAssembly.GetManifestResourceNames();
var stream = CurrentAssembly.GetManifestResourceStream(names.First());
//generic.xaml is an embedded resource in the current assembly
if (stream != null)
{
//created new generic.xaml here
var file = ApplicationData.Current.LocalFolder.CreateFileAsync("Generic.xaml", CreationCollisionOption.ReplaceExisting).Completed = (o, a) =>
{
var storageFile = o.GetResults();
var s = storageFile.OpenStreamForWriteAsync().Result;
var length = (int)stream.Length;
byte[] bytes = new byte[length];
int output = stream.Read(bytes, 0, length);
s.Write(bytes, 0, length);
s.Flush();
s.Dispose();
var asyncResult = this.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
var resourceDict = new ResourceDictionary();
var uri = new Uri("ms-appdata:///local/" + storageFile.Name);
resourceDict.Source = uri;
});
};
}
}
// OnApplyTemplate is not called without loading the style from generic.xaml
protected override void OnApplyTemplate()
{
base.OnApplyTemplate();
}
}
The below code I wrote in the custom control library's constructor, so that the control template can be set without generic.xaml
Here since the attribute TargeType="local:CustomControl1" is not present the control gets loaded properly, here since I loaded the style in the constructor, the OnApplyTemplate gets called
StringBuilder sb = new StringBuilder();
sb.Append(#"<ControlTemplate
xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation""
xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml""
xmlns:d=""http://schemas.microsoft.com/expression/blend/2008""
xmlns:mc=""http://schemas.openxmlformats.org/markup-compatibility/2006"">");
sb.Append(#"<Border Background=""{TemplateBinding
Background}""
BorderBrush=""{TemplateBinding BorderBrush}""
BorderThickness=""{TemplateBinding BorderThickness}"">
<Grid>
<Button x:Name=""Tbx1"" Content=""Hello World"" Foreground=""HotPink""
HorizontalAlignment=""Stretch"" VerticalAlignment=""Stretch""/>
</Grid>
</Border>");
sb.Append(#"</ControlTemplate>");
this.Template = (ControlTemplate)XamlReader.Load(sb.ToString());
but the problem is loading all the styles using XamlReader is not a good idea, unless we are out of Options. As there may be various dependent styles which too have to be loaded.
Check out how they do it in the WinRTXamlToolkit. They create the Generic.xaml for the project and include all control templates inside of separate styles in different ResourceDictionarys packaged next to the respective controls.
To put it more simply (for Templated controls, like you are using):
Make two files for each control, MyControl.cs and MyControl.xaml
In MyControl.cs in your MyControl constructor, set the StyleKey to be typeof(MyControl) (like you are doing currently).
Make sure there is a style for your control with TargetType set to the type of your control. Do the same thing for the ControlTemplate that you have as the Template property set in the Style.
In MyControl.xaml, make a ResourceDictionary that stores all of the necessary styles, templates, and resources.
In your Generic.xaml, create a MergedDictionaries tag under the root and create a ResourceDictionary for each control, setting the Source to the full path of MyControl.xaml
Set each of the .xaml files to be build type of Page with CustomTool set to MSBuild:Compile.
Hope this helps and Happy coding!
I want to write a test for a WPF application(Caliburn micro & autofac). The purpose of this test is to display a popup window from unit test case. I tried writing with stand alone WPF window and it worked:
But when I tried to integrate it to an existing solution which uses Caliburn micro & autofac and contains dictionaries and styles I got into some problems:
public MyViewModelTest()
{
this.repository = new MockRepository();
var eventAggregator = this.repository.Stub<IEventAggregator>();
//Other dependencies
viewModel = new MyViewModel(eventAggregator, other dependencies);
GenerateDummyData();
}
[Test]
public void OpenMyViewModelTest()
{
var uiThread = new Thread(Show);
uiThread.SetApartmentState(ApartmentState.STA);
uiThread.Start();
// Wait for the UI thread to finish
uiThread.Join();
}
private void Show()
{
//TODO make a new window to test and uncomment it.
var fg = new MyView { Height = 500, Width = 500, DataContext = viewModel };
//var fg = new MainView { Height = 500, Width = 500, DataContext = viewModel };
fg.ShowDialog();
}
Now if I execute the test from separate test project solution(Not with in UI project where view, viewmodels are available) I get an exception that:
SetUp : System.BadImageFormatException : Could not load file or assembly 'ABC.UIAssemblyName, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. An attempt was made to load a program with an incorrect format.
If I copy and run test from WPF UI project an empty window get lanuched.
So, I am wondering if I am missing some thing.
do I need to explicitly provide style resources, dictionaries and images etc to the WPF window with in the test.
A link on how write a test case for WPF window with caliburn micro would be a plus.
Thanks
I am trying to create some custom treeviews. Everything is working fine so far, but I got a little problem with styles. I have a simple "RedBackground" Style which I add to the resources of the Window. When adding normal elements, it works fine.
When using a custom item template to render treeview items, my resource is ignored. If I add the resource directly to the template it works fine (as marked in code)...
I obviously do not want to have to add styles to the ItemTemplate direclty, would be very complicated in further development. I think I am missing some kind of "Binding" or "Lookup"... I think it is related to dependency properties... Or something in this direction.
Perhaps anyone has more insights, here is the code creating the template (inside util class, but thats just to keep all clean):
var hdt = new HierarchicalDataTemplate(t)
{
ItemsSource = new Binding("Children")
};
var tb = new FrameworkElementFactory(typeof (TextBlock));
tb.SetBinding(TextBlock.TextProperty, new Binding("Header"));
hdt.VisualTree = tb;
// This way it works...
TextBlockStyles.AddRedBackground(hdt.Resources);
return hdt;
And here my very simple custom tree view
public class TreeViewCustom<T> : TreeView
{
public TreeViewCustom()
{
MinWidth = 300;
MinHeight = 600;
ItemTemplate = TreeViewTemplates.TryGetTemplate(typeof(T));
// This is ignored.... (Also when set as resource to window)
TextBlockStyles.AddRedBackground(Resources);
}
}
Ok, and to be sure, here the code which creates the Style:
public static class TextBlockStyles
{
public static void AddRedBackground(ResourceDictionary r)
{
var s = CreateRedBackground();
r.Add(s.TargetType, s);
}
private static Style CreateRedBackground()
{
var s = new Style(typeof(TextBlock));
s.Setters.Add(new Setter
{
Property = TextBlock.BackgroundProperty,
Value = new SolidColorBrush(Colors.Red)
});
return s;
}
}
Thanks for any tips...
Chris
Is this a problem with "inheritance"? Not all properties are inherited, read more here:
Property Value Inheritance: http://msdn.microsoft.com/en-us/library/ms753197.aspx