Проблема с получением designdata для отображения в предварительном просмотре дизайнера
Я пытаюсь отобразить данные дизайна в предварительном просмотре. UserControl работает нормально, когда я запускаю программу; Однако я не могу заставить дизайнера заполнить значениями.
Во-первых, мой UserControl с именем SignalStrengthControl
<UserControl x:Class="Connection.SignalStrengthControl"
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:Connection"
mc:Ignorable="d"
d:DesignHeight="53.833" d:DesignWidth="100.917"
d:DataContext="{d:DesignData Source=DesignData/SignalStrengthControlDesignData.xaml}">
<Grid Background="Transparent">
<Grid.Resources>
<SolidColorBrush x:Key="OnColor" Color="#FF4a6bc8"></SolidColorBrush>
<SolidColorBrush x:Key="OffColor" Color="#50FFFFFF"></SolidColorBrush>
<local:RatingConverter x:Key="RatingConverter" OnBrush="{StaticResource OnColor}" OffBrush="{StaticResource OffColor}" />
<Style TargetType="Rectangle">
<Setter Property="VerticalAlignment" Value="Bottom" />
</Style>
</Grid.Resources>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*"></ColumnDefinition>
<ColumnDefinition Width=".4*"></ColumnDefinition>
<ColumnDefinition Width="1*"></ColumnDefinition>
<ColumnDefinition Width=".4*"></ColumnDefinition>
<ColumnDefinition Width="1*"></ColumnDefinition>
<ColumnDefinition Width=".4*"></ColumnDefinition>
<ColumnDefinition Width="1*"></ColumnDefinition>
<ColumnDefinition Width=".4*"></ColumnDefinition>
<ColumnDefinition Width="1*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid Grid.Column="0">
<Grid.RowDefinitions>
<RowDefinition Height="4*"></RowDefinition>
<RowDefinition Height="1*"></RowDefinition>
</Grid.RowDefinitions>
<Rectangle Grid.Row="1"
Fill="{Binding Path=RatingValue, ConverterParameter=1, Converter={StaticResource RatingConverter}, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:SignalStrengthControl}}}"
Width="{Binding ActualWidth, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Grid}}"
Height="{Binding ActualHeight, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Grid}}"/>
</Grid>
<Grid Grid.Column="2">
<Grid.RowDefinitions>
<RowDefinition Height="3*"></RowDefinition>
<RowDefinition Height="2*"></RowDefinition>
</Grid.RowDefinitions>
<Rectangle Grid.Row="1"
Fill="{Binding Path=RatingValue, ConverterParameter=2, Converter={StaticResource RatingConverter}, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:SignalStrengthControl}}}"
Width="{Binding ActualWidth, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Grid}}"
Height="{Binding ActualHeight, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Grid}}"/>
</Grid>
<Grid Grid.Column="4">
<Grid.RowDefinitions>
<RowDefinition Height="2*"></RowDefinition>
<RowDefinition Height="3*"></RowDefinition>
</Grid.RowDefinitions>
<Rectangle Grid.Row="1"
Fill="{Binding Path=RatingValue, ConverterParameter=3, Converter={StaticResource RatingConverter}, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:SignalStrengthControl}}}"
Width="{Binding ActualWidth, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Grid}}"
Height="{Binding ActualHeight, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Grid}}"/>
</Grid>
<Grid Grid.Column="6">
<Grid.RowDefinitions>
<RowDefinition Height="1*"></RowDefinition>
<RowDefinition Height="4*"></RowDefinition>
</Grid.RowDefinitions>
<Rectangle Grid.Row="1"
Fill="{Binding Path=RatingValue, ConverterParameter=4, Converter={StaticResource RatingConverter}, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:SignalStrengthControl}}}"
Width="{Binding ActualWidth, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Grid}}"
Height="{Binding ActualHeight, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Grid}}"/>
</Grid>
<Grid Grid.Column="8">
<Grid.RowDefinitions>
<RowDefinition Height="0*"></RowDefinition>
<RowDefinition Height="5*"></RowDefinition>
</Grid.RowDefinitions>
<Rectangle Grid.Row="1"
Fill="{Binding Path=RatingValue, ConverterParameter=5, Converter={StaticResource RatingConverter}, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:SignalStrengthControl}}}"
Width="{Binding ActualWidth, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Grid}}"
Height="{Binding ActualHeight, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Grid}}"/>
</Grid>
</Grid>
</UserControl>
Вы можете видеть, что у меня есть игнорируемый DataContext, который указывает на некоторые данные проекта (нет проблем с поиском файла). Идея этого UserControl заключается в том, что он содержит свойство зависимости enum и имеет преобразователь enum, который управляет заполнением столбцов, что создает нечто вроде индикатора уровня сигнала Wi-Fi.
<local:SignalStrengthControlDesignData
xmlns:local="clr-namespace:Connection.DesignData"
xmlns:connection="clr-namespace:Connection"
xmlns:markup="http://schemas.microsoft.com/winfx/2006/xaml"
RatingValue="FourBars"
/>
<!--RatingValue="{markup:Static connection:SignalStrength.FourBars}"-->
Вот мой SignalStrengthControlDesignData.xaml. Я попробовал закомментированный код, и он тоже не работает. Я считаю, что "FourBars" интерпретируется как enum, потому что autocomplete говорит, что это член enum. Ниже приведен код данных проекта.
internal sealed class SignalStrengthControlDesignData
{
public SignalStrength RatingValue { get; set; }
}
Вот код для SignalStrengthControl, имеет свойство зависимости, перечисление и конвертер.
public partial class SignalStrengthControl
{
public SignalStrengthControl()
{
InitializeComponent();
}
public SignalStrength RatingValue
{
get { return (SignalStrength)GetValue(RatingValueProperty); }
set { SetValue(RatingValueProperty, value); }
}
// Using a DependencyProperty as the backing store for RatingValue. This enables animation, styling, binding, etc...
public static readonly DependencyProperty RatingValueProperty =
DependencyProperty.Register("RatingValue", typeof(SignalStrength), typeof(SignalStrengthControl), new UIPropertyMetadata(SignalStrength.ZeroBars));
}
public enum SignalStrength
{
ZeroBars,
OneBar,
TwoBars,
ThreeBars,
FourBars,
FiveBars
}
public class RatingConverter : IValueConverter
{
public Brush OnBrush { get; set; }
public Brush OffBrush { get; set; }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null || parameter == null)
{
return Brushes.Transparent;
}
// There are five bars in the xaml with each having a barNumber associated with it. The smallest bar
// on the left has a barNumber value of 1, the largest has 5.
int barNumber;
if (int.TryParse(parameter.ToString(), out barNumber))
{
var signalStrengthRating = (int)value;
if (barNumber <= signalStrengthRating)
{
return this.OnBrush;
}
return this.OffBrush;
}
return Brushes.Transparent;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Я также заменил это. OnBrush на Brushes.Wh независимо от цвета, и он все еще не появляется в конструкторе.
Я знаю, что один из способов показать что-то - это иметь FallBackValue, но в будущем мне может понадобиться что-то более сложное, чем это.
Открыто для всех предложений.
1 ответ
Я изменил реализацию, чтобы использовать пользовательский элемент управления, который переопределяет элемент управления ProgressBar WPF. Затем данные проекта оказались, как и ожидалось.