【问题标题】:Custom inherited button in items control, content not being set项目控件中的自定义继承按钮,未设置内容
【发布时间】:2017-07-07 08:53:51
【问题描述】:

(我正在使用 WPF 和 MVVM 模式)

首先,我继承了 Button 控件来创建自己的自定义按钮。这是因为我希望这个按钮有一些附加属性:

public class RangeButton : Button
{
    public Rank CardARank { get; set; }
    public Rank CardBRank { get; set; }
    public bool IsSuited { get; set; }
    public string ButtonContent { get; set; }

    public RangeButton(int i, int j, bool suited)
    {
        CardARank = GetRankFromInt(i);
        CardBRank = GetRankFromInt(j);
        IsSuited = suited;
        SetButtonContent();
    }

    public RangeButton()
    {
    }

    private Rank GetRankFromInt(int x)
    {
        return (Rank) x;
    }

    private void SetButtonContent()
    {
        ButtonContent = StaticGameHelpers.GetRangeSegmentString(CardARank, CardBRank, IsSuited);
    }
}

我在我的视图模型中初始化了一个 RangeButton 列表,它的每个属性都已正确设置 - 我最终得到了一个包含 169 个 RangeButton 的列表:

public List<RangeButton> RangeButtons
    {
        get { return _rangeButtons; }
        set
        {
            _rangeButtons = value;
            OnPropertyChanged("RangeButtons");
        }
    }

这是我的 XAML:

<ItemsControl x:Name="itemsControl" ItemsSource="{Binding RangeButtons}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <inheritedControls:RangeButton  Width="70" Height="50" Margin="3">
                    <ContentPresenter Content="{Binding ButtonContent, RelativeSource={RelativeSource Self}}"/>
                </inheritedControls:RangeButton>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <UniformGrid Columns="13" Rows="13"/>
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
    </ItemsControl>

正在显示所有 169 个按钮,但每个按钮都是空白的,没有内容。此外,宽度、高度和边距属性被忽略,这让我相信我的 xaml 存在问题,但我无法完全弄清楚。

我知道有一些类似的问题是这样问的,但没有一个使用自定义继承按钮。非常感谢任何帮助:)

【问题讨论】:

  • 如果您在视图模型中初始化 RangeButtons 列表,那么它不再是 MVVM。根据 MVVM,视图模型不应该知道视图。虽然您强制视图模型包含一些视图项(按钮)。
  • 您是否尝试过使用ObservableCollectionConcurrentBag 作为您的列表?这可能是它不刷新的原因,它绑定到一个简单的旧 List。只是猜测:)
  • @dymanoid 啊,是的,你是对的 - 感谢您指出这一点。您是否认为更好的方法是在我的 vm 中有一个自定义对象列表,例如 List ,它将包含与我的 RangeButton 相同的属性 - 然后在我的 xaml 中使用它作为项目源但重新模板化每个项目作为按钮?
  • 这是正确的方向。我怀疑你需要继承Button。您可以在 XAML 中应用 ControlTemplate 或使用附加属性(在您的自定义类中)。
  • @DanRayson 刚刚尝试过,但没有运气。我认为我需要一种全新的方法,正如 dymanoid 所指出的那样

标签: c# wpf xaml mvvm


【解决方案1】:

感谢@dymanoid 的一些建议,我采取了不同的方法。我放弃了从按钮控制理念中继承的全部内容,并简单地创建了一个自定义对象“RangeSegment”,它将取代我的 RangeButton 故障。在我的 VM 中,我存储了 RangeSegments 列表,并将它们用作我的 ItemsControl 的 ItemsSource。然后在每个项目的 Datatemplate 中,我添加了一个 Button,其中 content 属性绑定了每个 RangeSegment 中的属性

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多